gpt4 book ai didi

python - 用 Python 爬虫?

转载 作者:行者123 更新时间:2023-11-28 19:40:46 24 4
gpt4 key购买 nike

我想用python写一个爬虫。这意味着:我有一些网站主页的 url,并且我希望我的程序能够通过保留在网站中的链接爬过所有网站。我怎样才能轻松快速地做到这一点?我已经尝试过 BeautifulSoup,但它真的很消耗 CPU,而且在我的电脑上速度很慢。

最佳答案

我建议结合使用 mechanize 和 lxml.html。正如罗伯特金所建议的,机械化可能是浏览网站的最佳选择。为了提取元素,我会使用 lxml。 lxml 比 BeautifulSoup 快得多,可能是 python 可用的最快的解析器。 this link展示了针对 python 的不同 html 解析器的性能测试。就我个人而言,我不会使用 scrapy 包装器。

我还没有测试过,但这可能就是你要找的,第一部分直接取自 mechanize documentation . the lxml documentation也挺有帮助的。特别看看thisthis部分。

import mechanize
import lxml.html

br = mechanize.Browser()
response = br.open("somewebsite")

for link in br.links():
print link
br.follow_link(link) # takes EITHER Link instance OR keyword args
print br
br.back()

# you can also display the links with lxml
html = response.read()
root = lxml.html.fromstring(html)
for link in root.iterlinks():
print link

您还可以通过 root.xpath() 获取元素。一个简单的 wget 甚至可能是最简单的解决方案。

希望我能帮到你。

关于python - 用 Python 爬虫?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6649001/

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