gpt4 book ai didi

python - 用 python 抓取网页

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:34 26 4
gpt4 key购买 nike

我对抓取网络完全陌生,但我真的很想用 python 来学习它。我对 python 有基本的了解。

我无法理解抓取网页的代码,因为我找不到有关该代码使用的模块的良好文档。

该代码删除了 this 的一些电影数据网页

在评论“模式选择遵循 CSS 规则”后我陷入困境。

我想了解该代码背后的逻辑或一个好的文档来理解该模块。之前有我需要学习的主题吗?

代码如下:

import requests
from pattern import web
from BeautifulSoup import BeautifulSoup

url = 'http://www.imdb.com/search/title?sort=num_votes,desc&start=1&title_type=feature&year=1950,2012'
r = requests.get(url)
print r.url

url = 'http://www.imdb.com/search/title'
params = dict(sort='num_votes,desc', start=1, title_type='feature', year='1950,2012')
r = requests.get(url, params=params)
print r.url # notice it constructs the full url for you

#selection in pattern follows the rules of CSS

dom = web.Element(r.text)
for movie in dom.by_tag('td.title'):
title = movie.by_tag('a')[0].content
genres = movie.by_tag('span.genre')[0].by_tag('a')
genres = [g.content for g in genres]
runtime = movie.by_tag('span.runtime')[0].content
rating = movie.by_tag('span.value')[0].content
print title, genres, runtime, rating

最佳答案

这是 BeautifulSoup 的文档,这是一个 HTML 和 XML 解析器。

评论

selection in pattern follows the rules of CSS

表示字符串,如 'td.title''span.runtime'是 CSS 选择器,可帮助查找您要查找的数据,其中 td.title搜索 <TD>具有属性 class="title" 的元素.

该代码循环访问网页正文中的 HTML 元素,并通过 CSS 选择器提取标题、流派、运行时间和评级。

关于python - 用 python 抓取网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21071146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com