我正在尝试打印 donedeal 上每个项目的标题并从我自己的蜘蛛中复制代码,该代码在超频者中完美运行并相应地更改代码:
导入请求 从 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="card__body-title">安格斯小牛
”中刮取。最佳答案
您需要在请求中指定不同的用户代理,以使您看起来像是一个真实的人(即 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)
关于python - 美丽汤 <p> 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43356405/