漂亮的汤\u003b出现并弄乱了所有的东西?

2024-05-03 12:45:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在为顶级新闻网站制作网页刮板。python中的BeautifulSoup是一个很棒的工具,它让我能够用非常简单的代码获得完整的文章。但是

article_url='https://apnews.com/article/lifestyle-travel-coronavirus-pandemic-health-education-418fe38201db53d2848e0138a28ff824'

session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)


user_agent='Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'
request_header={ 'User-Agent': user_agent}
source=session.get(article_url, headers=request_header).text


soup = BeautifulSoup(source,'lxml')

#get all <p> paragraphs from article
paragraphs=soup.find_all('p')

#print each paragraph as a line
for paragraph in paragraphs:
    print(paragraph)

这在我尝试过的大多数新闻网站上都很有效,但由于某种原因,The AP网站根本没有给我任何输出。这是很奇怪的,因为完全相同的代码在其他10个站点上工作,比如纽约时报、WaPo和Hill。我知道为什么

它所做的是,当其他网站打印出所有段落时,它什么也不打印。除了当我查看变量时,我看到的是:

 address the pandemic.\u003c/p>\u003cdiv class=\"ad-placeholder\">\u003c/div>\u003cp>Instead, public schools 

显然,正在发生的是<;HTML符号被翻译为\u003b。正因为如此,find_all('p')无法正确地找到HTML标记。但出于某种原因,只有美联社网站在这样做。当我检查美联社网站时,他们的html与所有其他网站都有相同的符号

有人知道为什么会这样吗?或者我能做些什么来修复它?因为我很困惑


Tags: 代码httpsurladapter网站sessionarticleall
1条回答
网友
1楼 · 发布于 2024-05-03 12:45:11

至少对我来说,我必须用正则表达式提取一个包含数据的javascript对象,然后用json解析为json对象,然后获取与页面html相关的值,就像在浏览器中看到的那样,对其进行处理,然后提取段落。我删除了重试的东西;你可以很容易地重新插入

import requests
#from requests.adapters import HTTPAdapter
#from requests.packages.urllib3.util.retry import Retry
from bs4 import BeautifulSoup
import re,json

article_url='https://apnews.com/article/lifestyle-travel-coronavirus-pandemic-health-education-418fe38201db53d2848e0138a28ff824'
user_agent='Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'
request_header={ 'User-Agent': user_agent}
source = requests.get(article_url, headers=request_header).text
data = json.loads(re.search(r"window\['titanium-state'\] = (.*)", source, re.M).group(1))
content = data['content']['data']
content = content[list(content.keys())[0]]
soup = BeautifulSoup(content['storyHTML'])

for p in soup.select('p'):
    print(p.text.strip())

Regex:

enter image description here

相关问题 更多 >