admin管理员组

文章数量:1794759

requests

requests

1、安装

只支持python3.6及以上版本

pip install requests-html

2、使用方法

2.1构造请求

from requests_html import HTMLSession
session = HTMLSession()
# 用的文章阅读网的页面
r = session.get('.html')

2.1.1获取本页面所有的链接并返回一个列表, 保留了url在页面中原本的形式(已经自动去掉了html标签):

# 获取页面上的所有链接。
all_links = r.html.links
print(all_links)

2.1.2获取本页面所有的链接并返回一个列表, 自动将url转换为绝对路径形式(已经自动去掉了html标签):

# 获取页面上的所有链接,以绝对路径的方式。
all_absolute_links = r.html.absolute_links
print(all_absolute_links)

2.1.3通过css选择器选取Element对象**

    # 通过CSS找到新闻标签也就是css选择器形式news = r.html.find('.daohang > a')print(news)for new in news:# 获取一个Element对象内的文本内容print(new.text)# 获取一个Element对象的所有attributesprint(new.attrs)# 渲染出一个Element对象的HTML内容也就是从定位的地方打印所有代码:print(new.html)# 获取Element对象内的特定子Element对象print(new.find('a'))# 在获取的页面中查找文本匹配的是大括号中(纯文本专用)news = r.html.search('悟空你{}说')[0]print(news)# 直接打印文本标签所有内容(纯文本)sel = 'h3 > del'print(r.html.find(sel, first=True).text)# 你也可以获取到只包含某些文本的Element对象news = r.html.find('.daohang > a', containing='首页')print(news)

2.1.4通过xpath选择器选取Element对象

# 提取文本
t = r.html.xpath('//*[@id="wenzhangziti"]')
for i in t:    print(i.text)

2.2通过html获取渲染JavaScript渲染的文本

from requests_html import HTML
doc = """<a href='.html'>"""
html = HTML(html=doc)
script = """() => {return {width: document.documentElement.clientWidth,height: document.documentElement.clientHeight,deviceScaleFactor: window.devicePixelRatio,}}"""
val = html.render(script=script, reload=False)
print(val)

demo

 import requestsfrom requests_html import HTMLSessionsession = HTMLSession()"""下载图片"""# 保存图片到bg/目录def save_image(url, title):img_response = requests.get(url)with open('./bg/'+title+'.jpg', 'wb') as file:file.write(img_response.content)# 背景图片地址,这里选择1920*1080的背景图片url = ".html"session = HTMLSession()r = session.get(url)# 查找页面中背景图,找到链接,访问查看大图,并获取大图地址items_img = r.html.find('ul.clearfix > li > a')for img in items_img:img_url = img.attrs['href']if "/wallpaper_detail" in img_url:r = session.get(img_url)item_img = r.html.find('img.pic-large', first=True)url = item_img.attrs['src']title = item_img.attrs['title']print(url+title)save_image(url, title)

本文标签: Requests