【问题标题】:Python BeautifulSoup - Looping through multiple pagesPython BeautifulSoup - 循环多个页面
【发布时间】:2012-04-26 19:43:03
【问题描述】:

我试图首先从一个页面中获取所有链接,当获取“下一步”按钮的 URL 并继续循环直到没有更多页面为止。一直试图获得一个嵌套循环来实现这一点,但由于某种原因,BeautifulSoup 从不解析第二页..只有第一页然后停止..

很难解释,但这里的代码应该更容易理解我要解释的内容:)

#this site holds the first page that it should start looping on.. from this page i want to reach page 2, 3, etc.
   webpage = urlopen('www.first-page-with-urls-and-next-button.com').read()

soup = BeautifulSoup(webpage)

for tag in soup.findAll('a', { "class" : "next" }):

    print tag['href']
    print "\n--------------------\n"


#next button is relative url so append it to main-url.com
    soup = BeautifulSoup('http://www.main-url.com/'+ re.sub(r'\s', '', tag['href']))

#for some reason this variable only holds the tag['href']
    print soup

    for taggen in soup.findAll('a', { "class" : "homepage target-blank" }):
        print tag['href']

        # Read page found
        sidan = urlopen(taggen['href']).read()

# get title
        Titeln = re.findall(patFinderTitle, sidan)

        print Titeln

有什么想法吗?很抱歉英语不好,我希望我不会受到打击 :) 请询问我是否解释得不好,我会尽力解释更多。哦,我是 Python 新手——从今天开始(你可能已经猜到了:)

【问题讨论】:

  • 为什么第一次调用urlopen,第二次直接把URL传给BeatifulSoup()?

标签: python web-scraping beautifulsoup


【解决方案1】:

如果你在新的 url 上调用 urlopen 并将生成的文件对象传递给 BeatifulSoup,我想你会准备好的。那就是:

wepage = urlopen(http://www.main-url.com/'+ re.sub(r'\s', '', tag['href']))
soup = BeautifulSoup(webpage)

【讨论】:

  • 谢谢!现在它试图加载一个页面,现在我得到了一些非英文字符的 unicodeerror 原因嗯:
  • UnicodeError: URL u'main-url.com//bilf%C3%B6rs%C3%A4ljning/f\xf6retag/3' 包含非 ASCII 字符
  • 我很高兴它有帮助!如果您有时间,请检查此答案左侧的复选标记以将其标记为已接受的答案。您可能想提出一个关于 Unicode 错误的新问题,并且您需要在问题中包含实际 URL,以便我们自己查看数据。此外,请确保显示 Python 的完整回溯和相应的代码行。祝你好运!
【解决方案2】:

对于线路:

soup = BeautifulSoup('http://www.main-url.com/'+ re.sub(r'\s', '', tag['href']))

尝试:

webpage = urlopen('http://www.main-url.com/'+re.sub(r'\s','',tag['href'])).read()

soup = BeautifulSoup(webpage)

【讨论】:

  • @larsks - 是的,我知道,我们在一分钟内点击了回答按钮,所以我没有看到你的回答
猜你喜欢
  • 2019-05-26
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多