lxml爬取实验
1.豆瓣
爬取单个页面数据
import requests
from lxml import etree
#import os url = "https://movie.douban.com/cinema/nowplaying/yongzhou/"
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
req = requests.get(url=url,headers=headers)
text = req.text
dics = []
#将抓取下来的数据根据一定的规则进行提取
html = etree.HTML(text)
ul = html.xpath("//ul[@class='lists']")[0]
#print(etree.tostring(ul,encoding='utf-8').decode('utf-8'))
lis = ul.xpath("./li")
for li in lis:
title = li.xpath("@data-title")[0]
score = li.xpath("@data-actors")[0]
adress = li.xpath("@data-region")[0]
img_hai = li.xpath(".//img/@src")[0]
dic = {
'title':title,
'score':score,
'adress':adress,
'img':img_hai
}
dics.append(dic)
print(dics)
2.电影天堂
爬取多个页面数据
import requests
import json
from lxml import etree
url = "http://www.dytt8.net"
HEADERS = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
'Referer':'http://www.dytt8.net/html/gndy/dyzz/list_23_1.html'
} def get_url(urls):
response = requests.get(urls,headers=HEADERS)
text = response.text #请求页面
html = etree.HTML(text) #解析为HTML文档 html为Element对象 (可以执行xpath语法)
detail_urls = html.xpath("//table[@class='tbspan']//a/@href") #获取页面下的href
detail_urls = map(lambda urls:url+urls,detail_urls) #将detail_urls这个列表中每个url都扔给lambda这个函数合并 再将整个修改后的赋给detail_urls
return detail_urls def parse_detail_url(de_ur):
movie = {}
response = requests.get(de_ur,headers=HEADERS)
text = response.content.decode('gbk')
html = etree.HTML(text)
title = html.xpath("//div[@class='title_all']//font[@color='#07519a']/text()")[0] #获取标题
movie['title'] = title #放入字典
zoomE = html.xpath("//div[@id='Zoom']")[0]
img_hb = zoomE.xpath(".//img/@src")
cover = img_hb[0] #海报
#sst = img_hb[1] #电影截图
movie['cover'] = cover
#movie['sst'] = sst def parse_info(info,rule):
return info.replace(rule,"").strip() #.strip()把前后空格删掉
infos = zoomE.xpath(".//text()")
for index,info in enumerate(infos): #enumerate 索引序列(0 str 1 str 2 str)
if info.startswith("◎片 名"): #判断 以。。开始
info = parse_info(info,"◎片 名") #调用parse_info将"◎片 名"替换为无(没有)
movie['pian'] = info
elif info.startswith("◎年 代"):
info = parse_info(info, "◎年 代")
movie['year'] = info
elif info.startswith("◎产 地"):
info = parse_info(info, "◎产 地")
movie['adress'] = info
elif info.startswith("◎导 演"):
info = parse_info(info, "◎导 演")
movie['actor'] = info
elif info.startswith("◎类 别"):
info = parse_info(info, "◎类 别")
movie['lb'] = info
elif info.startswith("◎豆瓣评分"):
info = parse_info(info, "◎豆瓣评分")
movie['db'] = info
elif info.startswith("◎主 演"):
info = parse_info(info, "◎主 演")
actors = []
for x in range(index+1,len(infos)):
actor = infos[x]
if actor.startswith("◎"): #过滤简介部分
break
actors.append(actor)
movie['actors'] = actors
elif info.startswith("◎简 介"):
info = parse_info(info,"◎简 介")
for x in range(index+1,len(infos)):
profile = infos[x].strip()
if profile.startswith("【"): #过滤下载地址部分
break
movie['profile'] = profile
download_url = html.xpath("//td[@bgcolor='#fdfddf']/a/@href")[0] #下载地址
movie['download_url'] = download_url
return movie def write_to_file(content):
with open('result.txt','a',encoding='utf-8') as f:
f.write(json.dumps(content,ensure_ascii=False)+'\n') #ensure_ascii=False 输出为中文
f.close() def dianying():
urld = "http://www.dytt8.net/html/gndy/dyzz/list_23_{}.html" #这里用到了{} .format()的用法
movies = [] #定义一个列表
for x in range(1,8):
#第一个for循环用来控制7个页面
print(x)
urls = urld.format(x)
if x==5: #这里因为第5个页面出现报错信息 可能是编码问题 解决不了 所以我就过滤了第5页
continue
detail_ur = get_url(urls) #解析每页的详细信息
write_to_file("第%s页" % x)
for detail_url in detail_ur:
#第二个for循环用来遍历每个页
movie = parse_detail_url(detail_url)
movies.append(movie)
write_to_file(movie) if __name__ == '__main__':
dianying()
3.腾讯招聘
跟上一个电影天堂的代码差不多
import requests
import json
from lxml import etree
url = "https://hr.tencent.com/"
HEADERS = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
def get_url(urld):
response = requests.get(urld,headers=HEADERS)
text = response.text
html = etree.HTML(text)
detail_url = html.xpath("//tr[@class='even' or @class='odd']//a/@href")
detail_url = map(lambda x:url+x,detail_url) return detail_url def prease_url(detail_url):
dic = {}
#print(detail_url)
response = requests.get(detail_url,headers=HEADERS)
text =response.text
html = etree.HTML(text)
title = html.xpath("//tr[@class='h']//td[@class='l2 bold size16']//text()")[0]
dic['title'] = title #方法一 (死板)
adress = html.xpath("//tr[@class='c bottomline']//td//text()")[1]
dic['adress'] = adress
# 方法二 (简洁)
str = html.xpath("//tr[@class='c bottomline']//td")
leibie = str[1].xpath(".//text()")[1]
dic['leibie'] = leibie
nums = str[2].xpath(".//text()")[1]
dic['nums'] = nums
gz = html.xpath("//ul[@class='squareli']")
gzzz = gz[0].xpath(".//text()")
gzyq = gz[1].xpath(".//text()")
dic['工作职责'] = gzzz
dic['工作要求'] = gzyq
#print(dic)
return dic def write_to_file(content):
with open('tengxun.txt','a',encoding='utf-8') as f:
f.write(json.dumps(content,ensure_ascii=False)+'\n') #ensure_ascii=False 输出为中文
f.close()
def tengxun():
movies = []
urls = "https://hr.tencent.com/position.php?keywords=python&lid=0&tid=87&start={}#a"
for x in range(0,501,10): #步长为10
print(x)
urld = urls.format(x)
detail_urls = get_url(urld)
for detail_url in detail_urls:
movie = prease_url(detail_url)
movies.append(movie)
write_to_file(x)
write_to_file(movies) if __name__ == '__main__':
tengxun()
lxml爬取实验的更多相关文章
- 爬虫---lxml爬取博客文章
上一篇大概写了下lxml的用法,今天我们通过案例来实践,爬取我的博客博客并保存在本地 爬取博客园博客 爬取思路: 1.首先找到需要爬取的博客园地址 2.解析博客园地址 # coding:utf-8 i ...
- lxml的使用(节点与xpath爬取数据)
lxml安装 lxml是python下功能很丰富的XML和HTML解析库,性能非常的好,是对libxml3和libxlst的封装.在Windows下载这个库直接使用 pip install lxml ...
- 爬虫入门(四)——Scrapy框架入门:使用Scrapy框架爬取全书网小说数据
为了入门scrapy框架,昨天写了一个爬取静态小说网站的小程序 下面我们尝试爬取全书网中网游动漫类小说的书籍信息. 一.准备阶段 明确一下爬虫页面分析的思路: 对于书籍列表页:我们需要知道打开单本书籍 ...
- 用Python爬取了考研吧1000条帖子,原来他们都在讨论这些!
写在前面 考研在即,想多了解考研er的想法,就是去找学长学姐或者去网上搜索,贴吧就是一个好地方.而借助强大的工具可以快速从网络鱼龙混杂的信息中得到有价值的信息.虽然网上有很多爬取百度贴吧的教程和例子, ...
- Python3爬虫系列:理论+实验+爬取妹子图实战
Github: https://github.com/wangy8961/python3-concurrency-pics-02 ,欢迎star 爬虫系列: (1) 理论 Python3爬虫系列01 ...
- Python爬虫使用lxml模块爬取豆瓣读书排行榜并分析
上次使用了BeautifulSoup库爬取电影排行榜,爬取相对来说有点麻烦,爬取的速度也较慢.本次使用的lxml库,我个人是最喜欢的,爬取的语法很简单,爬取速度也快. 本次爬取的豆瓣书籍排行榜的首页地 ...
- lxml xpath 爬取并正常显示中文内容
在使用python爬虫提取中文网页的内容,为了能正确显示中文的内容,在转为字符串时一定要声明编码为utf-8,否则无法正常显示中文,而是显示原编码的字符,并没有正确转换.比如下面这个简单的爬取百度页面 ...
- Python爬虫——使用 lxml 解析器爬取汽车之家二手车信息
本次爬虫的目标是汽车之家的二手车销售信息,范围是全国,不过很可惜,汽车之家只显示100页信息,每页48条,也就是说最多只能够爬取4800条信息. 由于这次爬虫的主要目的是使用lxml解析器,所以在信息 ...
- Python爬虫爬取豆瓣电影之数据提取值xpath和lxml模块
工具:Python 3.6.5.PyCharm开发工具.Windows 10 操作系统.谷歌浏览器 目的:爬取豆瓣电影排行榜中电影的title.链接地址.图片.评价人数.评分等 网址:https:// ...
随机推荐
- C# http 性能优化500毫秒到 60 毫秒
偶然发现 C# 的 HttpRequest 要比 Chrome 请求同一Url 慢好多.C# HttpRequest 要500毫秒 而Chrome 只需要 39ms. 作为有责任感的 码农.这个 必须 ...
- JavaScript DOM 高级程序设计读书笔记二
响应用户操作和事件 事件就是操作检测与脚本执行的组合,或者基于检测到的操作类型在某个对象上调用事件侦听器(事件处理程序). 事件的类型 事件可以分为几种类型:对象事件,鼠标事件,键盘事件(只适用于do ...
- Spring Bean初始化之后执行指定方法
转: Spring Bean初始化之后执行指定方法 2017年07月31日 15:59:33 vircens 阅读数:24807 Spring Bean初始化之后执行指定方法 在运用Spring进 ...
- java 键盘录入(Scanner)
键盘录入(Scanner)• 键盘录入数据概述– 我们目前在写程序的时候, 数据值都是固定的, 但是实际开发中, 数据值肯定是变化的, 所以, 把数据改进为键盘录入, 提高程序的灵活性.• 如何实现键 ...
- JN_0007:微信昵称设置小数字
请复制下面背景色里面的数字符号 上标: ℡º ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ⁺ ⁻ ⁼ ⁽ ⁾ ⁿ ′ ½ 下标: ℡.₀ ₁ ₂ ₃ ₄ ₅ ₆ ₇ ₈ ₉ ₊ ₋ ₌ ₍ ₎ 复制上面那串数 ...
- Dynamic Clock in Terminal.
#!/bin/bash tput civis while [ 1 ] do tput clear # tput cup 10 20 info=$(date "+%Y-%m-%d %H:%M: ...
- python中的图像数据库PIL
from PIL import Image im = Image.open("图片路径") im.function() 常用的函数: 1.im.crop(x,y,x1,y1) 对图 ...
- HDU-6031 Innumerable Ancestors(二分+树上倍增)
题意 给一棵树,$m$次询问,每次询问给两个点集问从两个点集中各取一个点的$LCA$的最大深度. 思路 二分答案.对于某个二分过程中得到的$Mid$,如果可行则两个点集在$Mid$所在的深度存在公共的 ...
- vue-router组件重用 路由切换时的问题
当一个组件被重用时,切换路由,该组件不会被销毁.该组件的created也不会被调用,如果在created中有获取数据的操作,切换路由后,就不会再获取新的数据了,界面上就没有刷新. 其实官方文档就有解决 ...
- delphi 获取时间戳 如何得到 和 js 中 new Date().getTime();的 相同?
new Date().getTime(); //1533213439019 通过,启发 function DateTimeToUnix(const AValue: TDateTime): Int64 ...