python爬虫常用模块介绍(1)

对于一些简单的爬虫,python(基于python3)有更好的第三方库来实现它,且容易上手。

1,urllib.request

urllib.request最常见的用法是直接使用urllib.request.urlopen()来发起请求,但通常这样是不规范的

一个完整的请求还应该包括headers这样的信息传递,可以这样实现

import urllib.request
headers={"xxx":"xxx"}
url="http://xxxxxxx"
dic={"xx":"xx","xx":"xx"}

data=urllib.parse.urlencode(data).encode('utf-8')    #使用utf-8编码,将其转换为字节流,来提交字典参数
req=urllib.request.Request(url=url,headers=headers,method="post",data=data)

page=urllib.request.urlopen(req)
html=page.read().decode('utf-8')

通常防止爬虫被检测,我们需要规定headers,伪造爬虫头部信息,但此方法一般用途不大。

2,BeautifulSoup(美味汤)

beautifulsoup的功能很强大,利用它我们可以实现网页的轻松解析,省掉写很多正则表达式的麻烦。

它拥有几个强大的解析库,包括 内置的html解析器,lxml,html5lib。

一般默认的是html解析器 html.parser

最好的大概是lxml了

用法:

soup=BeautifulSoup(html,"html.parser")
################
soup=BeautifulSoup(html,"lxml")
###############3
soup=BeautifulSoup(html,"html5lib")

展现beautifulsoup强大的标签选择功能

获取某个html标签的属性:
print(soup.p['name'])

获取某个标签的内容:

print(soup.p.string)


获取某个标签内的所有内容,存入列表中

plist=soup.p.contents


find_all()标签选择器

例如我们要找到id=content 的div标签的内容

content=soup.find_all("div",{"id":"content"})
print(content)

select() --css选择器,包括(id值,class值,html标签等)

text=soup.select('.test_class')

这个几个选择器很有用,省去了编写正则表达式的繁琐。

你可能感兴趣的:(python爬虫常用模块介绍(1))