python抓取网页数据
解析效率:正则表达式>lxml>beautifulsoup
| 爬取方式 | 正则表达式 | lxml | beautifulsoup | 
|---|---|---|---|
| 解析效率 | 高 | 中 | 低 | 
| 复杂度 | 低 | 中 | 高 | 
| 代码 | urllib2.urlopen(urllist).read() | BeautifulSoup(html,'html.parser') | lxml.html.fromstring(html) | 
lxml库功能和使用类似BeautifulSoup库,不过lxml解析速度比beautifulsoup快。
爬取网页基础
requests_html下载
- 安装anaconda
- pip install pipenv
- 运行完后运行: pipenv install
- pip install requests_html- 爬取网站- 1 
 2
 3
 4
 5
 6
 7- from requests_html import HTMLSession 
 session = HTMLSession()
 url = 'https://www.codekp.cn/'
 r = session.get(url)
 print(r.html.text)
 print(r.html.links)
 print(r.html.absolute_links)
- r.html.text为网页文本内容
- r.html.links网页中包含的全部链接
- r.html.absolute_links为网页中包含的绝对路径- 输出结果为网站链接,和我们想要的内容并不完全相符,因此为了达到获取关键信息的目的,我们还需要进一步研究。跟Python说清楚我们要找的东西。这是网页抓取的关键。 
数据可视化pandas
只需要这一行命令,我们就能把刚才的列表变成数据框:
df = pd.DataFrame(get_text_link_from_sel(sel))
表头设置df.columns = ['text', 'link']
保存csv格式df.to_csv('output.csv', encoding='gbk', index=False)
代码
| 1 | from requests_html import HTMLSession | 
urllib 使用
| 1 | urllib.request.urlopen() 模拟浏览器向服务器发送请求 | 
通过urllib下载
| 1 | import urllib.request | 
BeautifulSoup爬取辛巴克菜单
| 1 | import urllib.request | 
lxml获取百度一下
| 1 | import urllib.request | 
我很可爱,请给我钱
- 本文链接:http://www.codekp.cn/2021/10/26/python%E6%8A%93%E5%8F%96%E7%BD%91%E9%A1%B5%E6%95%B0%E6%8D%AE/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。

您可以点击下方按钮切换对应评论系统。
GitHub Issues