【问题标题】:Beautiful soup returning empty in PythonAnywhere在 PythonAnywhere 中返回空的美丽汤
【发布时间】:2021-01-07 17:11:54
【问题描述】:

我有一个 bs4 应用程序,它会在这种情况下打印 igg-games.com 上的最新帖子
代码:

from bs4 import BeautifulSoup
import requests

def get_new():
    new = {}
    for i in BeautifulSoup(requests.get('https://igg-games.com/').text, features="html.parser").find_all('article'):
        elem = i.find('a', class_='uk-link-reset')
        new[elem.get_text()] = (elem.get('href'), ", ".join([x.get_text() for x in i.find_all('a', rel = 'category tag')]), i.find('time').get_text())
    return new
current = get_new()
new_item = list(current.items())[0]
print(f"Title: {new_item[0]}\nLink: {new_item[1][0]}\nCatagories: {new_item[1][1]}\nAdded: {new_item[1][2]}")

我的机器上的输出:

Title: Beholder�s Lair Free Download
Link: https://igg-games.com/beholders-lair-free-download.html
Catagories: Action, Adventure
Added: January 7, 2021

我知道它有效。但是,我的最终目标是将其变成 rss 提要条目。所以我将它全部插入到一个高级 PythonAnywhere 容器中。但是,我的函数 get_new() 返回 {}。有什么我需要做但我想念的事情吗?

【问题讨论】:

  • 可能来自requests.get() 的响应代码不是 200,因此该网站禁止来自特定 IP 地址的请求(在这种情况下为 PythonAnywhere)。您可能需要为此使用某种(旋转)代理,并尝试在请求的标头中指定一些 user agent
  • 这点很好,谢谢。关于我应该使用什么的任何建议?我从来不需要在这种情况下指定代理或用户代理。
  • 对于用户代理,请看这里stackoverflow.com/questions/27652543/… 这个关于轮换代理的教程也很有帮助:codelike.pro/create-a-crawler-with-rotating-ip-proxy-in-python
  • 解决了!非常感谢!我现在将添加这个问题的答案。
  • 不要忘记将问题标记为已解决 :)

标签: python beautifulsoup pythonanywhere


【解决方案1】:

感谢Dmytro O的帮助解决了。

由于 PythonAnywhere 很可能作为客户端被阻止,因此设置用户代理允许我接收来自预期站点的响应。

#the fix
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

response = requests.get(url, headers=headers)

当放置在我的代码中时

def get_new():
    new = {}
    for i in BeautifulSoup(requests.get('https://igg-games.com/', headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}).text, features="html.parser").find_all('article'):
        elem = i.find('a', class_='uk-link-reset')
        new[elem.get_text()] = (elem.get('href'), ", ".join([x.get_text() for x in i.find_all('a', rel = 'category tag')]), i.find('time').get_text())
    return new

这个方法是通过这个堆栈溢出帖子提供给我的:How to use Python requests to fake a browser visit a.k.a and generate User Agent?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2013-05-30
    • 2021-05-02
    相关资源
    最近更新 更多