python - 使用 Python 和 BeautifulSoup 为 Yahoo 和 Bing 生成多个页面的 URL

标签 python beautifulsoup

我想从不同来源抓取新闻。我找到了一种生成 URL 的方法,用于从 google 抓取多个页面,但我认为有一种方法可以生成更短的链接。

您能否告诉我如何生成用于抓取 Bing 和 Yahoo 新闻的多个页面的 URL,以及是否有办法使 google url 更短。

这是谷歌的代码:

from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}

term = 'usa'
page=0

for page in range(1,5):

    page = page*10

    url = 'https://www.google.com/search?q={}&tbm=nws&sxsrf=ACYBGNTx2Ew_5d5HsCvjwDoo5SC4U6JBVg:1574261023484&ei=H1HVXf-fHfiU1fAP65K6uAU&start={}&sa=N&ved=0ahUKEwi_q9qog_nlAhV4ShUIHWuJDlcQ8tMDCF8&biw=1280&bih=561&dpr=1.5'.format(term,page)
    print(url)

    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

这些是 yahoo 和 bing 的 URL,但针对 1 个页面:

雅虎:url = 'https://news.search.yahoo.com/search?q={}'.format(term) bing: url = 'https://www.bing.com/news/search?q={}'.format(term)

最佳答案

我不确定您是否在关注这个新闻缩短网址。

from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}

term = 'usa'
page=0

for page in range(1,5):

    page = page*10

    url = 'https://www.google.com/search?q={}&tbm=nws&start={}'.format(term,page)
    print(url)

    response = requests.get(url, headers=headers,verify=False)
    soup = BeautifulSoup(response.text, 'html.parser')

#雅虎:

from bs4 import BeautifulSoup
import requests

headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}

term = 'usa'
page=1
while True:

    url ='https://news.search.yahoo.com/search?q={}&pz=10&b={}'.format(term,page)
    print(url)
    page = page + 10
    response = requests.get(url, headers=headers,verify=False)
    if response.status_code !=200:
        break
    soup = BeautifulSoup(response.text, 'html.parser')

关于python - 使用 Python 和 BeautifulSoup 为 Yahoo 和 Bing 生成多个页面的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59047342/

相关文章:

python - 在 Python 中将字符串日期转换为时间戳

python - 如何解决 Telegraf 中的此错误?

python - 返回 pandas 中指定值的列名称

python - 将 python 代码模块化为可重用的函数

Python从网站上抓取fb评论

python - 比较数据框两列中的相同和不同

python - 在 Python 中的 Web 浏览器中打开和处理 URL 的最快方法

python - BeautifulSoup 在 Amazon EC2 机器上表现不同

python - 如何使用 Beautiful Soup 查找所有评论

python - 将标记字符串附加到 BeautifulSoup 中的标记