【问题标题】:Fetch only specific links using selenium in python在 python 中使用 selenium 仅获取特定链接
【发布时间】:2021-11-12 20:32:18
【问题描述】:

我正在尝试使用以下网页获取与 Apple 相关的所有新闻文章的链接:https://finance.yahoo.com/quote/AAPL/news?p=AAPL。但是中间也有很多广告链接,以及指向网站其他页面的其他链接。我如何选择性地只获取新闻文章的链接? 这是我目前写的代码:

driver = webdriver.Chrome(executable_path='C:\\Users\\Home\\OneDrive\\Desktop\\AJ\\chromedriver_win32\\chromedriver.exe')
driver.get("https://finance.yahoo.com/quote/AAPL/news?p=AAPL")
links=[]
for a in driver.find_elements_by_xpath('.//a'):
    links.append(a.get_attribute('href'))

def get_info(url):
    #send request   
    response = requests.get(url)
    #parse    
    soup = BeautifulSoup(response.text)
    #get information we need
    news = soup.find('div', attrs={'class': 'caas-body'}).text
    headline = soup.find('h1').text 
    date = soup.find('time').text
    return news, headline, date

任何人都可以指导如何执行此操作或可以帮助解决此问题的资源吗?谢谢!

【问题讨论】:

  • 可能有用:.//a[starts-with(@href,"/news") or starts-with(@href,"/m")]。您可以学习 XPath 语法。

标签: python selenium web-scraping beautifulsoup


【解决方案1】:

试试这个xpath 以获取该页面的所有新闻链接。

//li[contains(@class,'js-stream-content')]/div[@data-test-locator='mega']//h3/a
driver.implicitly_wait(10)
driver.maximize_window()

driver.get("https://finance.yahoo.com/quote/AAPL/news?p=AAPL")
time.sleep(10)
links = driver.find_elements_by_xpath("//li[contains(@class,'js-stream-content')]/div[@data-test-locator='mega']//h3/a")
for link in links:
    print(link.get_attribute("href"))

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 1970-01-01
    • 2016-04-18
    • 2022-07-13
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多