【发布时间】:2018-03-20 22:49:28
【问题描述】:
我尝试了不同的方法通过 BeautifulSoup、urllib 和 Selenium 从网站上抓取 Answer1 和 Answer2,但没有成功。这是简化版:
<div class="div1">
<p class="p1"></p>
<p class="p2">
<span>Question1</span>
<strong>Answer1</strong>
<br>
<span>Question2</span>
<strong>Answer2</strong>
<br>
在 selenium 中,我尝试查找 Question1,然后转到其父级并抓取 Answer1。下面是我使用的代码,虽然不正确。
browser.find_elements_by_xpath("//span[contains(text(), 'Question1')]/parent::p/following::strong")
在这种情况下,我相信 bs 比 selenium 更有效。你会如何在bs中做到这一点?谢谢!
编辑: @Juan 的解决方案非常适合我的示例。但是,我意识到它不适用于网站 https://finance.yahoo.com/quote/AAPL?p=AAPL 。任何人都可以从那里解析Consumer Goods 和Electronic Equipment 吗?使用 urllib.requests 会更好吗?谢谢。
【问题讨论】:
-
似乎你的问题不正确,因为你想
try to find Question1, then go to its parent and scrape Answer1,但你的代码尝试你做了相反的"//span[contains(text(), 'Question1')]/parent::p/following::strong" -
@DebanjanB 我的最终目标是抓取
Answer1和Answer2,我认为正确抓取这两者的最可靠方法是参考Question1。因此,我搜索Question1,然后返回其父级并找到两个答案。我的逻辑应该是正确的,但不确定我的代码。
标签: python selenium web-scraping beautifulsoup