之前断断续续学了一段时间的python基础,发现到了最后没有实践,连入门都算不上。所以这次找了本《Python爬虫从入门到实践》进行学习
由于之前有编程基础,所以这段就po几个练习题代码,还都挺简单的:
# 打印9*9乘法表 def multiplication(): for x in range(1,10): for j in range(1,10): print('%s * %s = %s'%(x,j,x*j)) multiplication()注意下面这段代码是有问题的
# 将符号变为空格 Python在for循环中直接修改列表元素值无效,需要用到索引 import re str='你好$$$我正在学Python@#@#现在需要&*&*&修改字符串' def replace(str): for x in str: if re.match(r'^[\$\#\@\&\*]+$',x): print(x) x=' '#无效 replace(list(str)) print(str)对于静态网页,直接使用内置模块requests访问网页资源即可,并且使用BeautifulSoup进行解析,即可类似于jQuery那样通过选择器解析到想要的数据。 比如下面这段代码,我就是通过以上工具,输出百度首页的热点(原来教程是爬豆瓣的top250,然而公司墙了豆瓣,就离谱。有本事哪天墙了百度)
# 由于上不了豆瓣 故只能爬百度首页的数据 from bs4 import BeautifulSoup import requests headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', 'host': 'www.baidu.com' } links = 'https://www.baidu.com' response = requests.get(links, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') # 参考https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#id48 aim_list=soup.find_all(attrs={"class" :'title-content-title'}) for i,x in enumerate(aim_list): print('%s. %s\n'%(i+1,x.get_text()))输出结果:
1. 美国将六家中国媒体列为外国使团 2. 19岁小伙骑行2300公里上大学 3. 特朗普曾在中国缴税?中方回应 4. 国泰港龙航空停止运营 5. 首批4000只蒙古国捐赠羊今日交付 6. 婺源鸳鸯湖迎今年首批越冬鸳鸯关于beautifulsoup的解析器,对比见官网文档: 推荐使用lxml作为解析器,因为效率更高
