【问题标题】:Shortened link not working with BeautifulSoup Python缩短的链接不适用于 BeautifulSoup Python
【发布时间】:2023-03-04 23:50:02
【问题描述】:

这段代码可以很好地从网站获取信息:

url = 'https://www.vogue.com/article/mamma-mia-2-here-we-go-again-review?mbid=social_twitter'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'}
response = requests.get(url, headers=headers)

soup = BeautifulSoup(response.text, "lxml")

title = soup.find("meta",  {"name": "twitter:title"})
title2 = soup.find("meta",  property="og:title")
title3 = soup.find("meta",  property="og:description")

print("TITLE: "+str(title['content']))
print("TITLE2: "+str(title2['content']))
print("TITLE3: "+str(title3['content']))

但是,当我用this shortened link 替换网址时,它会返回:

print("TITLE: "+str(title['content']))
TypeError: 'NoneType' object has no attribute '__getitem__'

【问题讨论】:

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

url-shortener 发送元刷新以重定向到所需的页面。这段代码应该会有所帮助:

from bs4 import BeautifulSoup
import requests
import re

shortened_url = '<YOUR SHORTENED URL>'

headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'}

response = requests.get(shortened_url, headers=headers)
soup = BeautifulSoup(response.text, "lxml")

while True:
    # is meta refresh there?
    if soup.select_one('meta[http-equiv=refresh]'):
        refresh_url = re.search(r'url=(.*)', soup.select_one('meta[http-equiv=refresh]')['content'], flags=re.I)[1]
        response = requests.get(refresh_url, headers=headers)
        soup = BeautifulSoup(response.text, "lxml")
    else:
        break

title = soup.find("meta",  {"name": "twitter:title"})
title2 = soup.find("meta",  property="og:title")
title3 = soup.find("meta",  property="og:description")

print("TITLE: "+str(title['content']))
print("TITLE2: "+str(title2['content']))
print("TITLE3: "+str(title3['content']))

打印:

TITLE: Mamma Mia! Here We Go Again Is the Only Good Thing About This Summer - Vogue
TITLE2: Mamma Mia! Here We Go Again Is the Only Good Thing About This Summer
TITLE3: Is it possible to change your country of origin to a movie sequel?

【讨论】:

    猜你喜欢
    • 2014-07-12
    • 2015-10-07
    • 1970-01-01
    • 2017-01-20
    • 2021-04-26
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多