卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35209本站已运行394

如何用 Python 抓取 javascript 网站?

如何用 python 抓取 javascript 网站?

问题内容

我正在尝试抓取一个网站。我尝试过使用两种方法,但两种方法都没有为我提供我正在寻找的完整网站源代码。我正在尝试从下面提供的网站 url 中抓取新闻标题。

网址:“https://www.todayonline.com/”

这是我尝试过但失败的两种方法。

方法一:美汤

tdy_url = "https://www.todayonline.com/"
page = requests.get(tdy_url).text
soup = beautifulsoup(page)
soup  # returns me a html with javascript text
soup.find_all('h3')

### returns me empty list []

方法2:selenium + beautifulsoup

tdy_url = "https://www.todayonline.com/"

options = Options()
options.headless = True

driver = webdriver.Chrome("chromedriver",options=options)

driver.get(tdy_url)
time.sleep(10)
html = driver.page_source

soup = BeautifulSoup(html)
soup.find_all('h3')

### Returns me only less than 1/4 of the 'h3' tags found in the original page source

请帮忙。我尝试过抓取其他新闻网站,这要容易得多。谢谢。


正确答案


您可以通过 api 访问数据(查看“网络”选项卡):

例如,

import requests
url = "https://www.todayonline.com/api/v3/news_feed/7"
data = requests.get(url).json()
卓越飞翔博客
上一篇: 使用 httptest 单元测试 http 请求重试
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏