用Python进行网络爬虫:如何获取文本

4

我想从网站上获取文本,但找不到方法。我该如何编写代码?

link="https://www.ynet.co.il/articles/0,7340,L-5553905,00.html"
response = requests.get(link)

soup = BeautifulSoup(response.text,'html.parser')
info = soup.find('div', attrs={'class':'text14'})
name = info.text.strip()
print(name)

这是它的外观: enter image description here 每次我都收不到任何东西。

你的截图显示了DOM,而beautifulsoup操作的是源代码。它们可能不同。 - Klaus D.
你尝试过这个response = requests.get(link).text吗? - Amir
@Amir 它给出了相同的结果。 - Michael
2个回答

2
import requests
from bs4 import BeautifulSoup
import json
link="https://www.ynet.co.il/articles/0,7340,L-5553905,00.html" 
response = requests.get(link)
soup = BeautifulSoup(response.text,'html.parser') 
info = soup.findAll('script',attrs={'type':"application/ld+json"})[0].text.strip()
jsonDict = json.loads(info)
print(jsonDict['articleBody'])

这个页面似乎把所有文章数据存储在<script>标签中的json中,所以请尝试这段代码:"最初的回答"。

在这种情况下怎么办呢:https://www.ynetnews.com/articles/0,7340,L-5554655,00.html?有没有想法如何获取文本?它在我的方式中不起作用,也不在你的方式中起作用。 - Michael

1

The solution is :

info = soup.find('meta', attrs={'property':'og:description'})

它给了我所需的文本。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接