【问题标题】:Extracting data from a meta tag beautifulsoup returning null从返回 null 的元标记 beautifulsoup 中提取数据
【发布时间】:2018-07-28 11:27:13
【问题描述】:

我试图从这个网站上获取汽车的行驶里程 https://cazana.com/uk/car/RA51GZJ

我想要的数据是里程(128,375 英里) 当我尝试抓取此页面时,我没有返回任何内容 我最初试图在没有运气的情况下跳过页面的正文

url = "https://cazana.com/uk/car/RA51GZJ"
page2 = requests.get(url)
soup2 = BeautifulSoup(page2.content, 'html.parser')
result = soup2.findAll('meta', attrs={'name': 'description'})

print (result)

返回 []

这是html文件

 <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="RA51GZJ - 2001 NISSAN ALMERA. Colour silver, 128,375 miles, 3 previous owners. Registered in Reading. Tax, MOT &amp; Vehicle history check available.">

谢谢

【问题讨论】:

  • page2有内容吗?
  • 我相信所以我在其他网站上使用了与此类似的代码并且它有效,但在这个特定的网站上我遇到了问题

标签: python html beautifulsoup meta


【解决方案1】:

您的请求不成功,这就是您没有找到正确标签的原因。
返回的内容是一个错误页面。
您可以通过将 User-Agent 标头更改为浏览器:

import requests
from bs4 import BeautifulSoup

url = 'https://cazana.com/uk/car/RA51GZJ'

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)'
    'AppleWebKit/537.36 (KHTML, like Gecko)'
    'Chrome/64.0.3282.167 Safari/537.36'
}

result = requests.get(url, headers=headers)
soup = BeautifulSoup(result.content, 'html.parser')
match = soup.find('meta', name='description')

if match:
    print(match.attrs['content'])
else:
    print('Request unsuccessful')

请注意,一次请求过多也会触发不成功的请求。

【讨论】:

  • 我在尝试此代码时收到此错误 AttributeError: 'NoneType' object has no attribute 'attrs'
  • 是的,那是因为您的请求被拒绝了。您可以稍后再试,或使用if match: 让您知道它不起作用。
  • 它对我有用,但当我一次使用脚本多次时就不行了。恐怕没有其他解决方案了¯\_(ツ)_/¯
  • 我会请朋友试试,因为我今天请求的网站太多了
  • 我应该像在 Windows 10 上一样将 Linux x86_64 更改为 Windows x86_64
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 2021-07-07
  • 2020-03-25
  • 2018-08-25
  • 1970-01-01
相关资源
最近更新 更多