【问题标题】:Web-scraping with beautifulsoup in different siblings在不同的兄弟姐妹中使用 beautifulsoup 进行网页抓取
【发布时间】:2018-03-20 22:49:28
【问题描述】:

我尝试了不同的方法通过 BeautifulSoup、urllib 和 Selenium 从网站上抓取 Answer1Answer2,但没有成功。这是简化版:

<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 GoodsElectronic Equipment 吗?使用 urllib.requests 会更好吗?谢谢。

【问题讨论】:

  • 似乎你的问题不正确,因为你想try to find Question1, then go to its parent and scrape Answer1,但你的代码尝试你做了相反的"//span[contains(text(), 'Question1')]/parent::p/following::strong"
  • @DebanjanB 我的最终目标是抓取Answer1Answer2,我认为正确抓取这两者的最可靠方法是参考Question1。因此,我搜索Question1,然后返回其父级并找到两个答案。我的逻辑应该是正确的,但不确定我的代码。

标签: python selenium web-scraping beautifulsoup


【解决方案1】:

我会这样做。我修改了关闭标签 p 和 div 的 html:

from bs4 import BeautifulSoup as BS
html = """
<div class="div1">
  <p class="p1"></p>
  <p class="p2">
    <span>Question1</span>
    <strong>Answer1</strong>
    <br>
    <span>Question2</span>
    <strong>Answer2</strong>
    <br>
    </p>
</div>
"""
soup = BS(html,'lxml')
QA = {x.text:y.text for x,y in zip(soup.select('span'),soup.select('strong'))}
print(QA)

【讨论】:

  • 感谢 Juan,但它返回 {}。有什么想法吗?
  • 在我的电脑里返回:{'Question1': 'Answer1', 'Question2': 'Answer2'}
  • 对不起,你是对的。我只是在网站上尝试,它没有返回任何内容。
  • 需要传递网站的html。我使用请求来获取它:import requests; url = 'http://www.example.com'; html = requests.get(url).text;然后用 BS 解析。如果页面有其他跨度或强标签,那么您必须分隔。在这种情况下可能是:QA = {x.text:y.text for x,y in zip(soup.select_one('div[class="div1"]').select('span'),soup.select_one('div[class="div1"]').select('strong'))}
  • 它返回AttributeError: 'NoneType' object has no attribute 'select',所以根据其他线程,网站中似乎没有这样的类? stackoverflow.com/questions/8949252/…
【解决方案2】:

div class="div1">

问题1 答案1
问题2 答案2

您只需使用 requests 和 beautifulsoup 导入并执行此操作

Import request
From bs4 import BeautifulSoup
Url ="google.com"
R = requests.get(url)
Soup = BeautifulSoup(url, "lxml")
 For link in links:
    Soup.find_all("span")
    Print(link.text())
For answers in answer:
    Soup.find_all("strong")
    Print(answes.text)

我的朋友正在做会员检查和一个元组,告诉你如何做到这一点。

【讨论】:

  • 它没有解决我在“编辑”部分的问题,但无论如何我都感谢您的帮助。
猜你喜欢
  • 2012-07-23
  • 1970-01-01
  • 2015-03-05
  • 2019-05-06
  • 1970-01-01
  • 2015-03-06
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多