我试图在donedeal上打印出每一项的标题,并从我自己的蜘蛛那里复制代码,这些代码在Over clockers上工作得完美无缺,并相应地更改代码:
从bs4导入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。提前谢谢。Edit2:我试着从"< p class=“卡__body标题”>Angus calves< /p >“中擦拭。
发布于 2017-04-11 21:30:41
在检查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检查代码,或者在遇到问题时打印出Soup!这可以帮助您清除所发生的事情,并向您展示哪些标记可用。
编辑:
虽然我不一定推荐它(刮擦是违反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错误!:)
有关更多信息,请参见这个答案
发布于 2017-04-11 22:19:45
您需要在请求中指定一个不同的用户代理,以使您看起来像是一个真实的人(即headers={‘User’:'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)https://stackoverflow.com/questions/43356405
复制相似问题