首先导入requests库:
import requests
导入etree:
etree中有两个常用的方法:etree.HTML()和etree.tostrint()。
其中etree.HTML()方法可以用来解析字符串格式的HTML文档对象,将传进去的字符串转变成_Element对象。作为_Element对象,可以方便的使用getparent()、remove()、xpath()等方法。(更加常用于网页爬虫实例中)
etree.tostrint()方法用来将_Element对象转换成字符串
from lxml import etree
获取浏览器的User-Agent和Referer:
我的是使用Google chrome浏览器,User-Agent是固定的,Referer就是你所要爬取的网页网址
User-Agent的目的:为了防止出现403的错误,一般都会首先设置一下请求头
Referer设置作用:将这个http请求发给服务器后,如果服务器要求必须是某个地址或者某几个地址才能访问,而你发送的referer不符合他的要求,就会拦截或者跳转到他要求的地址,然后再通过这个地址进行访问。
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Edg/94.0.992.50",
'Referer' : "https://movie.douban.com/",
}
一般获取方法:在需要爬取的页面 右键–>检查–>工具栏Network–>找到header选项,下滑到底部即可获取referer和User-Agent:
获取详细所爬取的网络网址:
url = 'https://movie.douban.com/cinema/nowplaying/nanchang/'
定义一个response抓取网页的源代码:
response = requests.get(url,headers=headers) text = response.text #print(response.text) html = etree.HTML(text)
获取网页的lists元素部分:
ul = html.xpath("//ul[@class = 'lists']")
#print(ul)
将ul下的li元素赋值给lis:
lis = ul[0].xpath("./li")
进行对获取下来的信息进行筛选和清洗:
movies = []
txt = ''
for li in lis:
#print(etree.tostring(li,encoding='utf-8').decode('utf-8'))
title = li.xpath("@data-title")[0]
score = li.xpath("@data-score")[0]
duration = li.xpath("@data-duration")[0]
region = li.xpath("@data-region")[0]
director = li.xpath("@data-director")[0]
actors = li.xpath("@data-actors")[0]
thumbnail = li.xpath(".//img/@src")[0]
movie = {
'title' :title,
'score' :score,
'duration' :duration,
'region' :region,
'director' :director,
'actors' :actors,
}
movies.append(movie)
txt += str(movie) + 'n'
爬取效果预览:
print(txt)
爬取的信息保存到txt文件操作:
file = open("new1.txt","w",encoding='utf-8')
file.write(txt)
file.close()



