前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python爬虫之BeautifulSoup

python爬虫之BeautifulSoup

作者头像
机器学习和大数据挖掘
发布2019-07-02 10:44:19
4610
发布2019-07-02 10:44:19
举报
文章被收录于专栏:数据挖掘数据挖掘

爬虫有时候写正则表达式会有假死现象

就是正则表达式一直在进行死循环查找

例如:https://social.msdn.microsoft.com/forums/azure/en-us/3f4390ac-11eb-4d67-b946-a73ffb51e4f3/netcpu100

所以一般在解析网页的时候可以用BeautifulSoup库来解决网页的正则表达式

网上对于BeautifulSoup的解释太复杂了

我就只是选取了我爬虫需要的部分来学习,其他的有需要再去学习,没需要就不浪费时间

最起码省心了很多

解释在注释里面都有了

一句一句的打印出来看就会明白的

代码语言:javascript
复制
 1 #!/usr/bin/python3.4
 2 # -*- coding: utf-8 -*-
 3 import urllib.request
 4 from bs4 import BeautifulSoup
 5 
 6 if __name__ == '__main__':
 7     url = "http://www.lenggirl.com/"
 8     headers = {
 9         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
10         'Accept': 'text/html;q=0.9,*/*;q=0.8',
11         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
12         'Accept-Encoding': 'gzip',
13         'Connection': 'close',
14         'Referer': None
15     }
16     data = urllib.request.urlopen(url).read()
17     # ('UTF-8')('unicode_escape')('gbk','ignore')
18     data = data.decode('UTF-8', 'ignore')
19     # 初始化网页
20     soup = BeautifulSoup(data, "html.parser")
21     # 打印整个网页
22     html = soup.prettify()
23     # 打印<head>...</head>
24     head = soup.head
25     # 打印<body>...</body>
26     body = soup.body
27     # 打印第一个<p>...</p>
28     p = soup.p
29     # 打印p的内容
30     p_string = soup.p.string
31     # soup.p.contents[0]为Aug 22, 2016
32     # soup.p.contents为[' Aug 22, 2016\n                        ']
33     p_string = soup.p.contents[0]
34     # 将body里面的所有头打印出来
35     for child in soup.body.children:
36         #print(child)
37         pass
38     # 将所有的<a>...</a>和<p>...</p>打印出来
39     a_and_p = soup.find_all(["a","p"])
40     # 找到<a>...</a>下所有的网址
41     for myimg in soup.find_all('a'):
42         img_src = myimg.get('href')
43         #print(img_src)
44     # 找到<a>...</a>下类为class_='a'下面的<img>...</img>里面的src
45     for myimg in soup.find_all('a', class_='a'):
46         img_src = myimg.find('img').get('src')
47     # 网页所有信息
48     #print(html)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-08-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档