python - 如何使用 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)
谢谢
解决方案
我会使用硒。请尝试以下代码:
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/
希望这可以帮助
推荐阅读
- javascript - button.addEventListener 在嵌套的 for 循环中不起作用
- mysql - 试图用 < 替换数据库中的一些字符串
- android - 您想将您的新应用程序与 cordova 集成以针对本机 ios 和 android 需要时间而没有响应
- angular - 角度:*ngFor trackby 日期
- javascript - ASP.NET Core 2 通过 AJAX 发布 JSON
- java - Java 9 未编译
- android - 从 firebase 检索数据需要一些时间才能加载到 recyclerview
- php - 根据 Woocommerce 父产品类别更改添加到购物车按钮文本
- jquery - .Net Core 2.0 Web API 无法在 Azure 中发布,因为 CORS 在响应标头中有多个 Access-Control-Allow-Origin
- java - NonGUIDriver java.lang.RuntimeException 中的错误:找不到 TestPlan 类!在 ubunto 上