gpt4 book ai didi

python - 使用 Python 循环抓取多个 URL,但当我遍历网站页码时数据没有改变?

转载 作者:太空宇宙 更新时间:2023-11-03 15:56:23 24 4
gpt4 key购买 nike

我正在使用 requests 和 beautifulsoup 搞乱网络抓取,当我试图通过在每个循环中添加 1 个页码来遍历多页留言板数据时,我得到了一些奇怪的结果。

下面的代码是一个示例,我在留言板上循环浏览第 1 页,然后循环浏览第 2 页。为了检查自己,我正在打印我正在点击的 URL,然后打印在该页面上找到的第一条记录. URL 看起来是正确的,但两者的第一个帖子是相同的。但是,如果我复制并粘贴这两个 URL,我肯定会在页面上看到一组不同的内容。

谁能告诉我这是否是我的代码有问题,或者它是否与给我这些结果的论坛上的数据结构有关?提前致谢!

from bs4 import BeautifulSoup

import requests

n_pages = 2
base_link = 'http://tigerboard.com/boards/list.php?board=4&page='

for i in range (1,n_pages+1):
link = base_link+str(i)
html_doc = requests.get(link)
soup = BeautifulSoup(html_doc.text,"lxml")
bs_tags = soup.find_all("div",{"class":"msgline"})
posts=[]
for post in bs_tags:
posts.append(post.text)
print link
print posts[0]

> http://tigerboard.com/boards/list.php?board=4&page=1
> 52% of all websites are in English, but - catbirdseat MU - 3/23/17 14:41:06
> http://tigerboard.com/boards/list.php?board=4&page=2
> 52% of all websites are in English, but - catbirdseat MU - 3/23/17 14:41:06

最佳答案

该网站的实现是虚假的。由于某些原因,它需要设置特定的 cookie PHPSESSID,否则无论 page 参数如何,它都不会返回第一页以外的其他页面。

设置这个 cookie 解决了这个问题:

from bs4 import BeautifulSoup

import requests

n_pages = 2
base_link = 'http://tigerboard.com/boards/list.php?board=4&page='

for i in range (1,n_pages+1):
link = base_link+str(i)
html_doc = requests.get(link, headers={'Cookie': 'PHPSESSID=notimportant'})
soup = BeautifulSoup(html_doc.text,"lxml")
bs_tags = soup.find_all("div",{"class":"msgline"})
posts=[]
for post in bs_tags:
posts.append(post.text)
print link
print posts[0]

另一种解决方案是使用 session因为(第一页的)第一个请求会将 cookie 设置为实际值,并将在以后的请求中发送。

调试很有趣!

关于python - 使用 Python 循环抓取多个 URL,但当我遍历网站页码时数据没有改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42985834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com