【问题标题】:BeautifulSoup scraping is returning {{ variable }} rather than the text shown on the pageBeautifulSoup 抓取返回 {{ variable }} 而不是页面上显示的文本
【发布时间】:2019-04-15 17:34:07
【问题描述】:

我正在尝试使用 BeautifulSoup 从网站上抓取一些数据,并且我得到的文本似乎是 Django 标签,例如{{ ResultLink }} 而不是我在查看页面源代码时可以看到的实际 URL。

我将如何取回页面上显示的文本? BeautifulSoup 中是否有可能?

我的代码是这样的:

    req = session.get(url, headers=headers)
    bsObj = BeautifulSoup(req.text, 'html.parser')

    if bsObj.find("div", {"id" : {"exactresult"}}) is not None:
        price = bsObj.find_all("div", {"class" : {"price-details"}})[0].get_text()
        link = bsObj.find_all("a", {"class" : {"btn-plate"}})[0].get_text()

pricelink 都返回 {{ }} 内的变量,而不是网页上显示的文本。

我在许多其他网站上使用了几乎相同的代码(具有相关的类名等)并且在那里工作正常,因此在我正在查看的网站上出现了一些特定的内容。

谢谢

【问题讨论】:

  • 可以提供网址吗?
  • 您好,我是url = https://www.regplates.com/search?search={0}'.format(reg)

标签: python-3.x beautifulsoup screen-scraping


【解决方案1】:

使用 Javascript 填充数据。您可以通过使用搜索词向其 API 发出 POST 请求来获取数据。这将返回一个json 响应,其中包含所有数据,包括顶部数据。

import requests
from bs4 import BeautifulSoup
#change 'ash1' to your search term
payload={"search":"ash1"}
req = requests.post('https://www.regplates.com/api/search',json=payload)
price=req.json()['data']['exact']['price']
link=req.json()['data']['exact']['link']
print(price,link,sep="\n")

输出

688800
/number-plate/ASH-1

json 响应可能非常大,具体取决于搜索词。理解它的一种简单方法是使用pprint

import pprint
...
pprint.pprint(req.json())

您也可以使用selenium 来获取数据。

【讨论】:

    猜你喜欢
    • 2017-06-12
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多