【发布时间】:2018-01-23 03:51:31
【问题描述】:
我是 Python 新手。我想提取谈论苹果的新闻文章。我的项目想从 BBC 网站获取仅关于苹果文章的文章。我的代码如下我抓取网站。但我无法确定如何我只收到 Apple 文章。任何人都可以帮助解决我的问题。
代码
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
#pass the URL
url = urlopen("http://www.bbc.com")
#read the source from the URL
readHtml = url.read()
#close the url
url.close()
#passing HTML to scrap it
soup = BeautifulSoup(readHtml, 'html.parser')
all_tag_a = soup.find_all("a", limit=10)
for links in all_tag_a:
#just pull the href part from each link
print(links.get('href'))
【问题讨论】:
-
您可能会使用以下 api 或类似的东西来获取与特定关键字(如 Apple)相关的文章,而不是尝试自己执行请求。 newsapi.org/s/bbc-news-api
-
@SuryaAvala 谢谢..我想抓取给定时间段的文章。你能进一步解释一下。我如何改变我的逻辑。
-
@SuryaAvala 我在这段代码中添加了
import requests url = ('https://newsapi.org/v2/everything?' 'q=Apple&' 'from=2018-01-23&' 'sortBy=popularity&' 'apiKey=42fd08167d994786b197aa193e26f954') response = requests.get(url) print( r.json)r 是什么。你能解释一下吗。我收到类似** print (r.json) NameError: name 'r' is not defined**