我正在尝试抓取一个网站。我尝试使用两种方法,但是两种方法都没有为我提供所需的完整网站源代码。我正在尝试从下面提供的网站网址中抓取新闻标题。
URL:“ https://www.todayonline.com/”
这是我尝试过但失败的两种方法。
=importxml("https://www.asx.com.au/asx/share-price-research/company/RMD", "//span[@ng-show='share.last_price']")
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 []
请帮助。我曾尝试抓取其他新闻网站,这非常容易。谢谢。
答案 0 :(得分:2)
例如,
import requests
url = "https://www.todayonline.com/api/v3/news_feed/7"
data = requests.get(url).json()
答案 1 :(得分:2)
有多种方法来收集包含Javascript的网页的内容。
selenium
与Firefox Web驱动程序配合使用phantomJS
使用无头浏览器requests
库进行API调用您必须先进行研究
答案 2 :(得分:2)
您要抓取的网站上的新闻数据是使用JavaScript(称为XHR -- XMLHttpRequest)从服务器上获取的。当页面正在加载或滚动时,它是动态发生的。因此该数据不会在服务器返回的页面内返回。
在第一个示例中,您仅获取服务器返回的页面-没有新闻,但使用应该获取它们的JS。请求和BeautifulSoup都不能执行JS。
但是,您可以尝试使用Python请求重现从服务器获取新闻标题的请求。请执行以下步骤:
复制请求链接(右键单击->复制->复制链接),并将其传递给requests.get(...)
。
获取.json()
的请求。它将返回一个易于使用的字典。为了更好地理解字典的结构,我建议使用pprint
而不是简单的打印。请注意,您必须先使用from pprint import pprint
。
以下是从页面主要新闻中获取标题的代码示例:
import requests
nodes = requests.get("https://www.todayonline.com/api/v3/news_feed/7")\
.json()["nodes"]
for node in nodes:
print(node["node"]["title"])
如果要在标题下抓取一组新闻,则需要更改请求URL中news_feed/
之后的数字(要获取它,您只需在DevTools中按“ news_feed”过滤请求即可然后向下滚动新闻页面。
有时,网站具有针对机器人的保护(尽管您尝试抓取的网站没有)。在这种情况下,您可能还需要执行these steps。
答案 3 :(得分:2)
我会建议您一种非常简单的方法,
import requests
from bs4 import BeautifulSoup as bs
page = requests.get('https://www.todayonline.com/googlenews.xml').content
soup = bs(page)
news = [i.text for i in soup.find_all('news:title')]
print(news)
输出
['DBS named world’s best bank by New York-based financial publication',
'Russia has very serious questions to answer on Navalny - UK',
"Exclusive: 90% of China's Sinovac employees, families took coronavirus vaccine - CEO",
'Three militants killed after fatal attack on policeman in Tunisia',
.....]
此外,如果需要,您可以检查XML页面以获取更多信息。
P.S。报废任何网站之前,请务必检查其合规性:)