【问题标题】:find page number in ajax sites for Web Scraping在 ajax 站点中查找页码以进行 Web Scraping
【发布时间】:2020-04-12 08:38:17
【问题描述】:

我想用 python 和BeautifulSoup 抓取一个网站,但我找不到页码,我只能抓取网站的第一页,我认为这个网站使用了 Ajax,当我更改页面时 URL地址不变。

这是网站的链接:

https://ihome.ir/sell-residential-apartment/th-tehran

这是我的代码,我想抓取这个网站的 20 页,抓取房屋的详细信息,如价格、地基等

import requests
from bs4 import BeautifulSoup

response = requests.get("https://ihome.ir/sell-residential-apartment/th-tehran")


soup = BeautifulSoup(response.json(), "html.parser")
prices = soup.select('.sell-value')
titles = soup.select('.title')

homes_prices = []
for home in prices:
    homes_prices.append(int(''.join(filter(str.isdigit, home.getText()))))


homes_titles = []
for title in titles:
    homes_titles.append(title.getText())

res = dict(zip(homes_titles, homes_prices))

for key, value in res.items():
    p = str(res[key])
    if len(str(res[key])) <= 2:
        p += '000000000'
    if len(str(res[key])) > 2:
        p += '000000'

    print(key.strip(), int(p))

【问题讨论】:

  • 这里是check
  • @αԋɱҽԃαмєяιcαη 谢谢,如何通过此链接使用请求?
  • 将此链接与reuqests 一起使用,就像任何其他链接r = requests.get(link) 一样。这个页面似乎不需要任何特殊的标题。不同之处仅在于您可以获得结果r.json() 而不是r.text,并且您不必使用BeautifulSoup
  • @furas tnx 为您解答,但我想用漂亮的汤刮掉网站,我编辑我的问题。我该怎么做?
  • 如果您可以直接以 JSON 格式获取它,那么不要浪费时间在 BeautifulSoup 上。

标签: python ajax web-scraping beautifulsoup python-requests


【解决方案1】:

没有必要使用BeautifulSoup 作为您正在寻找的data。已在 JSON 字典中呈现!

这里是Back-EndAPI,从中获取数据。

当您正在寻找 scrape 20 页面和包含 24 项目的每个页面时。

所以它是24 * 20 = 480,所以我将每页的结果调整为480,并调用API 一次比多次循环页面要好。

现在你有一个JSON dict,你可以访问和提取你想要的任何东西!

import requests


params = {
    'is_sale': '1',
    'source': 'website',
    'paginate': '480',
    'page': '1',
    'locations[]': 'iran.th.tehran',
    'property_type[]': 'residential-apartment'
}


def main(url):
    r = requests.get(url, params=params).json()
    for item in r['data']:
        print(item.keys())


main("https://scorpion.ihome.ir/v1/flatted-properties")

【讨论】:

  • tnx 为您解答,但我想通过美丽的汤刮网站,我编辑我的问题。我该怎么做?
  • @Ariaban 很好,只是不要继续循环,edit 你的问题,给我看一个简单的所需输出。
  • 我想为该站点的 20 个页面执行我的代码。但是我不知道这个站点的第二个和第三个以及...二十个的url地址。 response = requests.get("ihome.ir/sell-residential-apartment/th-tehran")
  • @Ariaban 询问最终所需的输出?这是什么
  • 在最后我抓取了网站的 20 页并将其添加到数据库中,我只是在响应中遇到了页码问题。我的代码没有问题。
猜你喜欢
  • 2016-07-09
  • 1970-01-01
  • 2019-08-24
  • 1970-01-01
  • 2013-01-17
  • 2017-06-28
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多