美丽的汤<p>参数

时间:2017-04-11 21:21:39

标签: python python-3.x beautifulsoup

我正在尝试打印donedeal上每个项目的标题,并复制我自己的蜘蛛中的代码,该代码在Overclockers上运行完美无缺,并相应地更改代码:

导入请求 来自bs4 import BeautifulSoup

def donedeal(max_pages):
    for i in range(1, max_pages+1):
        page = (i - 1) * 28
        url = 'https://www.donedeal.ie/farming?sort=publishdate%20desc&start={}'.format(page) # http:/?...
        source_code = requests.get(url)
        plain_text = source_code.content
        soup = BeautifulSoup(plain_text, "html.parser")
        for title in soup("p", {"class": "card__body-title"}):
            x = title.text
            print(x)

donedeal(1)

页码如下:0, 28, 56..所以我必须在功能顶部相应地更改页码。

问题是什么都没有打印,我得到退出代码0。 提前致谢。 编辑2:我试图从“&lt; p class =”card__body-title“&gt; Angus calves&lt; / p&gt;”中搜集。

2 个答案:

答案 0 :(得分:3)

您需要在请求中指定一个不同的User-Agent,使其看起来像是一个真实的人(即headers = {'User-Agent':'Mozilla / 5.0'})。完成后,您的代码将按预期工作。

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup

def donedeal(max_pages):
    for i in range(1, max_pages+1):
        page = (i - 1) * 28
        req = Request('https://www.donedeal.ie/farming?sort=publishdate%20desc&start={}'.format(page), headers={'User-Agent': 'Mozilla/5.0'})
        plain_text = urlopen(req).read()
        plain_text.decode('utf-8')
        soup = BeautifulSoup(plain_text, "html.parser")
        for title in soup("p", {"class": "card__body-title"}):
            x = title.text
            print(x)

donedeal(1)

答案 1 :(得分:2)

当检查pdb中的汤(你的for循环之前的断点)时,我发现:

(Pdb++) p soup
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n\n<html><head>\n<title>410 
Gone</title>\n</head><body>\n<h1>Gone</h1>\n<p>The requested 
resource<br/>/farming<br/>\nis no longer available on this server and there is 
no forwarding address.\nPlease remove all references to this resource.
</p>\n</body></html>\n

这可能意味着有一些防刮措施!该网站检测到您正在尝试使用python进行抓取,并将您发送到无法获取任何数据的页面。

将来,我建议使用pdb检查代码,或者在遇到问题时打印出汤!这有助于清理发生的事情,并向您展示可用的标签

编辑:

虽然我不一定会推荐它(刮擦是针对donedeal的服务条款),但有一种方法可以解决这个问题。

如果你想生活在野外,你可以让requests模块HTTP请求看起来像来自真实用户,而不是脚本。您可以使用以下方法执行此操作:

import requests
from bs4 import BeautifulSoup

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'}

def donedeal(max_pages):
    for i in range(1, max_pages+1):
        page = (i - 1) * 28
        url = 'https://www.donedeal.ie/farming?sort=publishdate%20desc&start={}'.format(page) # http:/?...
        source_code = requests.get(url, headers=headers)
        plain_text = source_code.content
        soup = BeautifulSoup(plain_text, "html.parser")
        for title in soup("p", {"class": "card__body-title"}):
            x = title.text
            print(x)

donedeal(1)

我所做的就是告诉requests模块使用headers中提供的标头。这使得请求看起来像是来自使用Firefox的Mac。

我对此进行了测试,看起来它打印出了你想要的标题,没有410错误! :)

有关详情,请参阅this answer

相关问题