python - BeautifulSoup 两次打印相同的结果
问题描述
URL = "https://bitcointalk.org/index.php?board=1.0"
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
numberOfPages = 0
currentPage = 0
counter = 1
for blabla in soup.find_all("a" , attrs={"class" : "navPages"})[-2]:
numberOfPages = int(blabla.string)
print("Pages count: " + str(numberOfPages))
for i in range(0,numberOfPages):
URLX = "https://bitcointalk.org/index.php?board=1."+ str(currentPage)
print(URLX)
print("------------------------------------------------- Page count is: " + str(counter))
counter += 1
currentPage += 20
page1 = requests.get(URLX)
soup1 = BeautifulSoup(page1.content, 'html.parser')
time.sleep(1.0)
for random in soup1.find_all("span", attrs={"id": re.compile("^msg")}):
for b in random.find_all('a', href=True):
print (b.string)
我正在尝试浏览“比特币讨论板”上的所有页面,并从每一页打印主题的名称。它正在工作,但由于某种原因,它会不断打印主题的名称两次......同时浏览不同的页面。例如:
网址(首页): https ://bitcointalk.org/index.php?board=1.0
将打印其实际内容:
ABC123
另一个话题
然后...即使 URL 更改为第二页,它仍然会打印相同的主题。
然后所有其他页面都会发生同样的事情。每页打印两次(即使 URL 正在更改)。
有什么想法吗?这是我第一次使用 Python 和 BeautifulSoup。
解决方案
不同页面的链接如下,即它们的增量为.40
:
https://bitcointalk.org/index.php?board=1.0
https://bitcointalk.org/index.php?board=1.40
https://bitcointalk.org/index.php?board=1.80
https://bitcointalk.org/index.php?board=1.120
因此,它应该currentPage += 40
代替 current currentPage += 20
。