Python-S9-Day122-Python爬虫
-
11 初识爬虫
11 初识爬虫
12 今日作业
11.1 初识黄页;

11.2 互联网就是一张大的蜘蛛网;
网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。
11.3 自动爬取想要得到的文章;
11.4 资讯网站,抽屉新热榜,今日头条,易车网,爱卡网等数据来源,进行爬取,然后在自家网站呈现;
11.5 爬取汽车之家的首页的新闻文章、标题以及图片等内容;
import requests from bs4 import BeautifulSoup # 汽车之家使用的是GBK编码: response = requests.get("https://www.autohome.com.cn/news/") # response = requests.get("https://www.jd.com/") response.encoding = "gbk" # print(response.text) # find方法找到与之相匹配的第一个标签; soup = BeautifulSoup(response.text, "html.parser") div = soup.find(name='div', attrs={'id': 'auto-channel-lazyload-article'}) # print(div) li_list = div.find_all(name='li') for li in li_list: # print("汽车之家的li标签!",li) title = li.find(name="h3") if not title: continue # print(title) p = li.find(name='p') a = li.find(name='a') print(title.text) url = "https:" + a.attrs.get('href') print("文章的URL地址:", url) # print('https:'+a.attrs.get('href')) print(p.text) img = li.find(name='img') src = "https:" + img.get('src') print("图片的URL地址:", src) # 再次发起请求,下载图片; file_name = src.rsplit('/', maxsplit=1)[1] ret = requests.get(src) with open(file_name, 'wb') as f: f.write(ret.content)
11.6 通过代码伪造请求,伪装浏览器,进行页面的爬取;
-
requests,伪造浏览器发起http请求;
-
bs4,将html格式的字符串解析成对象,对象.find/find_all方法的使用;
12 今日作业
12.1 Flask程序实现爬虫采集以展示;
12.2 功能:
- Flask目录结构;
- SQLAchemy存储数据;
12.3 页面
- 数据框:https://www.autohome.com.cn/news/
“终身”学习,生活充满诗意!
浙公网安备 33010602011771号