“驾驭requsets_html“_夜爬tom资讯

驾驭requests_html新库的感受

	近来,一直在潜心钻研大神新开发的requests_html,体会她的同步与异步的差别以及对动态加载的虐杀.让我找到了一库爬遍天下的快感.同时,作为一个自学的菜鸟,为自己的这点点进步很是沾沾自喜,今晚上我又拿tom资讯练了把手.重点想把requests_html综合的网页解析部分拿来与大家共享.

requests_html在网页解析中的那点猫腻

获取元素
request-html支持CSS选择器和XPATH两种语法来选取HTML元素。首先先来看看CSS选择器语法,它需要使用HTML的find函数,该函数有5个参数,作用如下:

selector,要用的CSS选择器;
clean,布尔值,如果为真会忽略HTML中style和script标签造成的影响(原文是sanitize,大概这么理解);
containing,如果设置该属性,会返回包含该属性文本的标签;
first,布尔值,如果为真会返回第一个元素,否则会返回满足条件的元素列表;
_encoding,编码格式。
下面是几个简单例子:# 首页菜单文本
print(r.html.find(‘div#menu’, first=True).text)
#首页菜单元素
print(r.html.find(‘div#menu a’))
#段子内容print(list(map(lambda x: x.text, r.html.find(‘div.content span’))))
在网页其他单字段解析中,相信大家一看就会,但对于多段落的文字部分的精确解析着实让人抓狂.今天我用map(lambda x: x.text,r.html.find(‘xxxx’ ))表达式在解析网页中彻底解决了list中[<Element ‘a’ href=’/’ rel=(‘nofollow’,)>, <Element ‘a’ href=’/hot/’>, <Element ‘a’ href=’/imgrank/’>, <Element ‘a’ id=‘highlight’ href=’/text/’>, <Element ‘a’ href=’/history/’>, <Element ‘a’ href=’/pic/’>, <Element ‘a’ href=’/textnew/’>]的文本提取.希望这部分能帮助其他朋友解决爬取文字中遇到的问题.

下面送上代码:

import logging
from requests_html import AsyncHTMLSession
from fake_useragent import UserAgent
import random
import json
from pymongo import MongoClient

asession = AsyncHTMLSession()
ua = UserAgent()
client = MongoClient(host=‘localhost’, port=27017)
db = client.root
url = ‘http://news.tom.com/’
headers = {‘useragent’: ua.random}
url1 = ‘http://news.tom.com/json/show1372.json?s=1612594258268’
#制定日志文件
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s|%(lineno)s |%(message)s",
filename=‘2_6_1.log’, filemode=‘w’, encoding=‘utf8’)

async def main():
try:
headers[‘Referer’] = url
with await asession.get(url=url, headers=headers)as resp:
# await resp.html.arender()
all = resp.html.find(’.main_text .item-container’)
for e in all:
title = e.find(‘ul .item-right a h4’, first=True)
if title == None:
continue
task={‘title’:title.text}
# logging.info(title.text)
href = e.find(‘ul .item-right a’, first=True)
task[‘href’] = ‘http:’+href.attrs[‘href’]
await get_next_request(asession, task)
# logging.info(task)

except Exception as e:
    logging.error(e)

async def get_next_request(asession,task):
try:
with await asession.get(url=task[‘href’],headers=headers)as re:
all_data=re.html.find(’.content_news_box’,first=True)
img=all_data.find(’.news_box_text center img’,first=True).attrs[‘src’]
task[‘img’]=img
author=all_data.find(’.news_box_infor .infor_from a’,first=True).text
task[‘author’]=author
content=list(map(lambda x: x.text,all_data.find(’.news_box_text p’)))
task[‘content’]=’’.join(content).strip()

        if db.tb_tomnews.insert_one(task):
            logging.info('储存成功',task)
        else:
            logging.error('储存失败',task)
        
except Exception as e:
    logging.error(e)

asession.run(main)

插入链接与图片

链接: [link](“驾驭requsets_html“_夜爬tom资讯
“驾驭requsets_html“_夜爬tom资讯
“驾驭requsets_html“_夜爬tom资讯
“驾驭requsets_html“_夜爬tom资讯
“驾驭requsets_html“_夜爬tom资讯
“驾驭requsets_html“_夜爬tom资讯
https://www.csdn.net/).

总结:

通过这个小例子,我学会了日志调用,mongoDB的存储/调用.等知识点.要知道对于我这个自学者来说,这些东西真是来之不易啊,这是我网上查资料,听公开课不断练习索取得的.我会继续学习Python的相关知识的.

上一篇:requests保存图片


下一篇:requsets请求方式和xpath解析器的基本用法