Python爬虫

三. 爬虫三大库

2018-02-14  本文已影响0人  橄榄的世界

1.Requests库

import requests
获取Response内容:r = requests.get("http://www.baidu.com")

2.BeautifulSoup库

from bs4 import BeautifulSoup
解析方法:soup = BeautifulSoup(r.text,"lxml")
soup的类型为:<class 'bs4.element.Tag'>
select()方法: soup.select(div.item a h1)
find()方法:soup.find('div',class='item')
find_all()方法:soup.find_all('div',class='item')

获取文本的两种方法 : soup.get_text()或soup.text
其中,soup.text是bs4.element.Tag类的属性,而 soup.get_text()是bs4.element.Tag类的方法。

实例:

import requests
from bs4 import BeautifulSoup

url = 'https://movie.douban.com/subject/6874741/'
r = requests.get(url)
soup = BeautifulSoup(r.text,"lxml")

film_name = soup.select('#content > h1 > span')[0].text
director = soup.select('#info > span:nth-of-type(2) > span.attrs > a')[0].text   #此处用copy selector会弄错,需参考xpath路径
actors = soup.select('#info > span.actor > span.attrs')[0].text
#actors = soup.select('#info > span.actor > span.attrs')[0].get_text()   #等同于上一句
movie_time = soup.select('#info > span:nth-of-type(13)')[0].text                 #此处用copy selector会弄错,需参考xpath路径

print ('电影名:',film_name)
print ('导演:',director)
print ('主演:',actors)
print ('片长:',movie_time)

结果:

电影名: 无问西东
导演: 李芳芳
主演: 章子怡 / 黄晓明 / 张震 / 王力宏 / 陈楚生 / 铁政 / 祖锋 / 米雪 / 王盛德 / 韩童生 / 王鑫 / 郑铮 / 章泽天 / 黄梦莹 / 林美秀 / 保罗·菲利普·克拉克 / 胡家华 / 伊娜 / 吴谨言 / 纪帅 / 王天泽 / 伍麟凯 / 都金翰
片长: 138分钟

3.Lxml库

from lxml import etree
解析方法:selector = etree.HTML(r.text)
修正html代码:result = etree.tostring(selector)
xpath()方法:selector.xpath('div/a/h1/text()')

实例:

import requests
from lxml import etree

url = 'https://movie.douban.com/subject/6874741/'
r = requests.get(url)
#print(r.status_code)
selector = etree.HTML(r.text)

#text()提取标签的文本内容
film_name = selector.xpath('//*[@id="content"]/h1/span[1]/text()')
director = selector.xpath('//*[@id="info"]/span[1]/span[2]/a/text()')    
actors = selector.xpath('//*[@id="info"]/span[3]/span[2]/a/text()')
movie_time = selector.xpath('//*[@id="info"]/span[13]/text()')

print ('电影名:',film_name)
print ('导演:',director)
print ('主演:',actors)
print ('片长:',movie_time)

结果同上。

上一篇 下一篇

猜你喜欢

热点阅读