gpt4 book ai didi

python - 如何使用 python BeautifulSoup 分页抓取页面

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

我是编程新手,在使用 python BeautifulSoup 抓取所有页面时遇到问题。我想出了如何抓取第一页,但我不知道如何抓取所有页面。

Here is the code:
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from urllib2 import urlopen
import json
from BeautifulSoup import BeautifulSoup

defaultPage = 1
items = []
url = "https://www.nepremicnine.net/oglasi-prodaja/ljubljana-mesto/stanovanje/%d/"

def getWebsiteContent(page=defaultPage):
return urlopen(url % (page)).read()

def writeToFile(content):
file = open("nepremicnine1.json", "w+")
json.dump(content, file)
# file.write(content)
file.close()

def main():

content = getWebsiteContent(page=defaultPage)
soup = BeautifulSoup(content)
posesti = soup.findAll("div", {"itemprop": "itemListElement"})

for stanovanja in posesti:
item = {}
item["Naslov"] = stanovanja.find("span", attrs={"class": "title"}).string
item["Velikost"] = stanovanja.find("span", attrs={"class": "velikost"}).string
item["Cena"] = stanovanja.find("span", attrs={"class": "cena"}).string
item["Slika"] = stanovanja.find("img", src = True)["src"]

items.append(item)

writeToFile(items)

main()

所以我想循环遍历,因此 url %d 每次都会增加 1,因为页面编号为 2,页面编号为 3 等等。

非常感谢所有帮助。

最佳答案

您没有增加 defaultPage 变量。

您尝试执行的方式是正确的。每次完成抓取页面时,您只需增加 defaultPage 变量

def main():
while (defaultPage <= numPages) # Loop through all pages. You also need to define the value of numPages.
content = getWebsiteContent(page=defaultPage)
soup = BeautifulSoup(content)
posesti = soup.findAll("div", {"itemprop": "itemListElement"})

for stanovanja in posesti:
item = {}
item["Naslov"] = stanovanja.find("span", attrs={"class": "title"}).string
item["Velikost"] = stanovanja.find("span", attrs={"class": "velikost"}).string
item["Cena"] = stanovanja.find("span", attrs={"class": "cena"}).string
item["Slika"] = stanovanja.find("img", src = True)["src"]

items.append(item)

writeToFile(items)
defaultPage += 1

我认为这应该有效

关于python - 如何使用 python BeautifulSoup 分页抓取页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44329883/

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