gpt4 book ai didi

python - 按下一页链接爬行

转载 作者:行者123 更新时间:2023-12-04 16:22:50 26 4
gpt4 key购买 nike

我正在编写一个爬虫来提取维基百科上的食谱 href 链接。根据我的实现,如何继续添加链接直到到达最后一页?注意:下一页链接的标题是“下一个 200”。

链接在此处列出:http://en.wikibooks.org/wiki/Category:Recipes

def fetch_links(self, proxy):
"""Extracts filtered recipe href links

Args:
proxy: The configured proxy address.

Raises:
ValueError: If proxy is not a valid address.

"""
if not self._valid_proxy(proxy):
raise ValueError('invalid proxy address: {}'.format(proxy))
self.browser.set_proxies({'http': proxy})
page = self.browser.open(self.wiki_recipes)
html = page.read()

link_tags = SoupStrainer('a', href=True)
soup = BeautifulSoup(html, parse_only=link_tags)
recipe_hrefs = r'^\/wiki\/Cookbook:(?!recipes|table_of_contents).*$'
return [link['href'] for link in soup.find_all(
'a', href=re.compile(recipe_hrefs, re.IGNORECASE))]

最佳答案

根据我在您的评论中建议的方法,这里是使用 urllib 的代码示例和 re ,这些技术可在您的代码中重用。

您创建一个函数并将 url 作为参数,最初传递起始 url,并抓取所有配方链接并使用正则表达式附加到全局列表。然后得到 (下一个 200) link 作为参数并调用相同的函数。 try/except用尽并导出列表。

由于您有一个没有显示代码的类,我将跳过所有 classproxy部分,我们开始:

#!/usr/bin/python

import urllib
import re

base_url = 'http://en.wikibooks.org/wiki/Category:Recipes'
next_base = 'http://en.wikibooks.org'
recipes = []

# this is just the sample function
# you should handle your proxy logic here too
def get_links(url):
request = urllib.urlopen(url)
content = request.read()
# I just use one-off re expression
links = re.findall(r'/wiki/Cookbook:(?!Recipes)(?!Table_of_Contents).*" ', content)

global recipes
recipes += links

try:
# again, one-off re expression
next_url = re.findall(r'/w/index.*>next 200', content)[0].split('\" ')[0]
print "fetching next url: " + str(next_base + next_url)
return get_links(next_base + next_url)
except IndexError:
print "all recipes fetched."
print recipes
return

if __name__ == '__main__':
print "start fetching..."
get_links(base_url)

希望你得到所需的技术。

关于python - 按下一页链接爬行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26453429/

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