首页 > 解决方案 > 如何使用 python beautiful-soup 从网站上抓取 url?

问题描述

我试图从特定链接中抓取一些 url,我使用 beautiful-soup 来抓取这些链接,但我无法抓取这些链接。在这里,我附上了我使用过的代码。实际上,我想从“fxs_aheadline_tiny”类中抓取网址

import requests
from bs4 import BeautifulSoup

url = 'https://www.fxstreet.com/news?q=&hPP=17&idx=FxsIndexPro&p=0&dFR%5BTags%5D%5B0%5D=EURUSD'
r1 = requests.get(url)
coverpage = r1.content
soup1 = BeautifulSoup(coverpage, 'html.parser')
coverpage_news = soup1.find_all('h4', class_='fxs_aheadline_tiny')
print(coverpage_news)

谢谢

标签: pythonpython-3.xweb-scrapingbeautifulsoup

解决方案


我会使用硒。请尝试以下代码:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

#open driver
driver= webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.fxstreet.com/news?q=&hPP=17&idx=FxsIndexPro&p=0&dFR%5BTags%5D%5B0%5D=EURUSD')

# Use ChroPath to identify the xpath for the 'page hits'
pagehits=driver.find_element_by_xpath("//div[@class='ais-hits']")

# search for all a tags
links=pagehits.find_elements_by_tag_name("a")

# For each link get the href
for link in links:
    print(link.get_attribute('href'))

它完全符合您的要求:它会删除您搜索页面上的所有网址/链接(这也意味着指向作者页面的链接)。

您甚至可以考虑自动化浏览器并浏览搜索页面结果。请参阅 Selenium 文档:https ://selenium-python.readthedocs.io/

希望这可以帮助


推荐阅读