python网络爬虫入门

1、获取网页源码

from urllib import request
fp=request.urlopen("https://blog.csdn.net")
content=fp.read()
fp.close()

2、从源码中提取信息

这里需要使用可以从HTML或者xml文件中提取数据的python库,beautiful soup
安装该库:

pip3 install beautifulsoup4
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
for x in soup.findAll(name='a'): # 找出所有的a标签
	print('attrs:',a.attrs) # 输出a标签的属性

#利用正则,找出所有id=link数字 标签
for a in soup.findAll(attrs={'id':re.compile('link\d')})
	print(a)

3、对信息进行处理

可以写入文件,也可以做进一步处理,例如清洗

示例代码如下:

from bs4 import BeautifulSoup
from urllib import request
import re
import chardet
import sys
import io
#改变标准输出的默认编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') 
fp=request.urlopen("https://blog.csdn.net")
html=fp.read()
fp.close()
# 判断编码方式
det = chardet.detect(html)
# 使用该页面的编码方式
soup = BeautifulSoup(html.decode(det['encoding']))
# 找出属性为href=http或者href=https开头的标签
for tag in soup.findAll(attrs={'href':re.compile('http|https')}):
	print(tag)
	with open(r'C:\Users\Van\Desktop\test.csv', 'a+') as file:
		content = tag.attrs['href'] + '\n'
		file.write(content) #写入文件

猜你喜欢

转载自blog.csdn.net/qq_27466827/article/details/84112716