取消时无法获取标题内容

2024-03-29 10:25:26 发布

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

我是一个新手,但我尝试了各种方法来解决这个问题,但没有得到预期的结果。我想取消这个网站https://www.accesswire.com/newsroom/我想取消所有的标题,标题显示时,我检查他们在浏览器中,但与bs4或硒刮后,我没有得到完整的源代码页,也没有得到标题以及。你知道吗

我试过time.sleep(10),但对我来说也不管用。我用selenium来获取页面,但这对我也不起作用。 分区列-15 w列w列9 这是标题所在的类div

ua     = UserAgent()
header = {'user-agent':ua.chrome}
url = "https://www.accesswire.com/newsroom/"
response = requests.get(url, headers=header)
time.sleep(12)
soup = BeautifulSoup(response.content, 'html.parser')
time.sleep(12)
headline_Div = soup.find("div",{"class":"column-15 w-col w-col-9"})
print(headline_Div)

我只想得到这个页面上所有的标题和标题链接 或者至少应该显示一个完整的页面源代码,这样我就可以自己操作它了。 谢谢


Tags: httpsdivcomurl标题源代码timeresponse
1条回答
网友
1楼 · 发布于 2024-03-29 10:25:26

你不需要硒。只需使用页面使用的更高效的请求和API

import re
import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.accesswire.com/api/newsroom.ashx')
p = re.compile(r" \$\('#newslist'\)\.after\('(.*)\);")
html = p.findall(r.text)[0]
soup = bs(html, 'lxml')
headlines = [(item.text, item['href']) for item in soup.select('a.headlinelink')]
print(headlines)

正则表达式解释:

试试regex here

网友
2楼 · 发布于 2024-03-29 10:25:26

如果pull和parse不起作用是因为内容是动态的,那么实际的浏览器需要selenium来为您生成内容

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://www.accesswire.com/newsroom/')
headline_links = driver.find_elements_by_css_selector('a.headlinelink')
headlines = [link.get_attribute('textContent') for link in headline_links]

相关问题 更多 >