Web Crawler - TooManyRedirects:超过30个重定向。 (蟒蛇)

时间:2015-06-01 13:05:42

标签: python web-crawler

我试过按照其中一个youtube教程 但是我遇到了一些问题。 有人能帮忙吗? 我是python的新手,我知道有一两个相似的问题,但是,我读过并且不明白。 有人可以帮我吗? 感谢

import requests
from bs4 import BeautifulSoup
def trade_spider(max_pages):
    page = 1
    while page <= max_pages:
        url = "https://www.thenewboston.com/forum/home.php?page=" + str(page)
       source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.findAll('a', {'class': 'post-title'}):
            href = link.get('href')
            print(href)
        page += 1
trade_spider(2)

运行程序后,我收到了如下错误。

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/Basic/WebCrawlerTest.py", line 19, in <module>
    trade_spider(2)
  File "C:/Users/User/PycharmProjects/Basic/WebCrawlerTest.py", line 9, in trade_spider
    source_code = requests.get(url)
  File "C:\Users\User\AppData\Roaming\Python\Python34\site-packages\requests\api.py", line 69, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\User\AppData\Roaming\Python\Python34\site-packages\requests\api.py", line 50, in request
    response = session.request(method=method, url=url, **kwargs)
  File "C:\Users\User\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 465, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\User\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 594, in send
    history = [resp for resp in gen] if allow_redirects else []
  File "C:\Users\User\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 594, in <listcomp>
    history = [resp for resp in gen] if allow_redirects else []
  File "C:\Users\User\AppData\Roaming\Python\Python34\site-packages\requests\sessions.py", line 114, in resolve_redirects
    raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects)
requests.exceptions.TooManyRedirects: Exceeded 30 redirects.

2 个答案:

答案 0 :(得分:1)

好吧,您尝试抓取的网页看起来很简单:尝试将https://www.thenewboston.com/forum/home.php?page=1放入您的网络浏览器中:当我尝试使用Chrome时,收到错误消息:

  

此网页有重定向循环

     

ERR_TOO_MANY_REDIRECTS

您必须自己确定如何在抓取工具中处理此类损坏的网页。

答案 1 :(得分:1)

该论坛的网址已更改

对您的代码进行两次修改

  

更改了论坛   1.url(https://www.thenewboston.com/forum/recent_activity.php?page=“+   STR(页))
  allow_redirects = False(如果有的话,禁用重定向)。

import requests
from bs4 import BeautifulSoup
def trade_spider(max_pages):
    page = 1
    while page <= max_pages:
        url = "https://www.thenewboston.com/forum/recent_activity.php?page=" + str(page)
        print url
        source_code = requests.get(url, allow_redirects=False)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        for link in soup.findAll('a', {'class': 'post-title'}):

            href = link.get('href')
            print(href)
        page += 1
print trade_spider(2)