requests_html 包爬虫求助

2019-09-29 10:25:22 +08:00
 334862132
今天学习 requests_html 包 网上找俩个爬虫 分别爬慕课网和 51cto 的爬虫 结果发现 传入的时候一个可以直接传 res.html,另一个必须要用 PyQuery 转换一下 res.text 才能传入 这个是为什么啊 上代码。。。。
抓取 51 的
from requests_html import AsyncHTMLSession # 导入异步模块

asession = AsyncHTMLSession()

BASE_URL = "http://edu.51cto.com/courselist/index-p{}.html"

async def get_html():
for i in range(1,2):
r = await asession.get(BASE_URL.format(i)) # 异步等待
get_item(r.html)

def get_item(html):
c_list = html.find('.cList',first=True)
if c_list:
items = c_list.find('.cList_Item')
for item in items:
title = item.find("h3",first=True).text # 课程名称
href = item.find('h3>a',first=True).attrs["href"] # 课程的链接地址
dict = {
"title":title,
"href":href,
}
print(dict)


if __name__ == '__main__':
result = asession.run(get_html)

抓取慕课的

from requests_html import AsyncHTMLSession
from pyquery import PyQuery as pq

s = AsyncHTMLSession()
url = "https://www.imooc.com/course/list?page={i}"

async def get_html():
for i in range(1,2):
res = await s.get(url.format(i=i))
d = pq(res.text)
get_content(d)

def get_content(d):
courses = d.items(".course-card-container")
for course in courses:
title = course.find(".course-card-name").text() # 查找 title
des = course.find(".course-card-desc").text()

dict = {
"title":title,
"des":des
}
print(dict)

if __name__ == '__main__':
ret = s.run(get_html)
2528 次点击
所在节点    Python
6 条回复
fifa666
2019-09-29 11:05:10 +08:00
你打印输出,看一下呗
334862132
2019-09-29 11:11:16 +08:00
@fifa666 主要打印输出没看出来有什么区别 刚在别人指点下又用 requests 包试了一下 俩个地址返回的都是 html 不是 json 我一下就懵逼了。。。
silencefent
2019-09-29 11:15:21 +08:00
不要用 requests_html,就用 requests
334862132
2019-09-29 11:53:33 +08:00
@silencefent requests_html 封装 requests 自带异步多线程 用 requests 还要封装多线程 还要搞 i/o 异步,多麻烦,本来这个我也搞出来了,就是想不明白为什么传的东西不一样...
334862132
2019-09-29 11:55:17 +08:00
51 的 html 打印出来是这个 <HTML url='https://edu.51cto.com/courselist/index-p1.html'>
慕课的 html 打印出来是 <HTML url='https://www.imooc.com/course/list?page=1'>
sherlockwhite
2019-09-29 13:38:19 +08:00
“多麻烦”?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/605282

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX