requests.exceptions.InvalidURL:解析失败:python 中的 <Response [200]>

requests.exceptions.InvalidURL: Failed to parse: <Response [200]> in python

所以我现在写了这段代码,现在从 cnn 获取特定主题的新闻我在这里遇到错误是代码:

from bs4 import BeautifulSoup
import requests
import csv
import re

serch_term = input('What News are you looking for today? ')

url = f'https://edition.cnn.com/search?q={serch_term}'
page = requests.get(url)
doc = BeautifulSoup(page, "html.parser")

page_text = doc.find_all(class_="cnn-search__result-headline")
print(page_text)

但是我遇到了这个错误,我已经尝试了很多方法,但是 none 其中对我有用

What News are you looking for today? coronavirus
Traceback (most recent call last):
  File "c:\Users\user\Desktop\Informatik\Praktik\Projekte\Python\news_automation\main.py", line 10, in <module>
    doc = BeautifulSoup(page, "html.parser")
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\bs4\__init__.py", line 312, in __init__
    elif len(markup) <= 256 and (
TypeError: object of type 'Response' has no len()

我已经用谷歌搜索并尝试了很多东西,但 none 其中有效果 有人知道出了什么问题吗?所以,

我自己测试过,你应该把这行代码改成如下:

从:来源 = requests.get(url) 到:页面 = source.text

补充信息:

我发现您可以按如下方式使用此 search.api.cnn.io 并在我编写代码时直接生成 json,您需要做的是提取您需要的信息。

url = f"search.api.cnn.io/content?q={serch_term}"

extra_parameters_sample_url"https://search.api.cnn.io/content?q=coronavirus&sort=newest&category=business,us,politics,world,opinion,health&size=100&from=0"

source = requests.get(url).text 
json_reponse = json.loads(source)

至于为什么您的原始代码不起作用,page 变量是响应 object 但 Beautiful soup 期待 HTML.

这是通过 doc = BeautifulSoup(page.text, "html.parser")

修复的

但是,cnn 似乎正在使用 javascript 库来呈现他们的网站,这会使 scraping 数据稍微困难一些,因为您需要使用 [=14 这样的工具=] 到 运行 无头浏览器以呈现内容。

根据@Lenatian 的回答,最简单的方法是调用 CNN api 而根本不必抓取数据,我更新了代码以检查错误并检查是否没有API 的结果。 如果成功,它将打印出附加到搜索查询的标题列表。

您还可以打印 results 的值以查看从 api.

发回的所有其他数据
import requests

# serch_term = input('What News are you looking for today? ')
search_term = "Corona Virus"
url = f"https://search.api.cnn.io/content?q={serch_term}"

response = requests.get(url)

if not response.ok:
  raise Exception("There was an error calling the API")

response = response.json()
results = response.get("result")

if not results:
  print("Could not find any results for your search term :(")

print([result.get("headline") for result in results])