【问题标题】:CSS select with beautifulsoup4 doesn't work使用 beautifulsoup4 进行 CSS 选择不起作用
【发布时间】:2014-05-01 11:04:28
【问题描述】:

我试过bs4,但是select方法不行。

我的代码有什么问题?

import requests
import bs4

def main():
    r = requests.get("http://nodejs.org/download/")
    soup = bs4.BeautifulSoup(r.text)

    selector = "div.interior:nth-child(2) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(3) > a:nth-child(1)"
    print(soup.select(selector)[0].text)

if __name__ == "__main__":
    main()

【问题讨论】:

  • BeautifulSoup 4 似乎从 3 回归,它不支持它应该支持的一些选择器。例如,h1.a.b 与我的 <h1 class="a b"> 不匹配。

标签: python web-scraping beautifulsoup


【解决方案1】:

此页面上的答案不同于在浏览器中查看而不是使用 bs 解析。 看看你的 r.text 并从那里解析。

响应类似于

<div class="interior row">
<div id="installers">
<ul>
<li>
<a href="http://nodejs.org/dist/v0.10.26/node-v0.10.26-x86.msi">
<img alt="" height="50" src="http://nodejs.org/images/platform-icon-win.png" width="45">
              Windows Installer
              <small>node-v0.10.26-x86.msi</small>
</img></a>
</li>
<li>
<a href="http://nodejs.org/dist/v0.10.26/node-v0.10.26.pkg">
<img alt="" height="50" src="http://nodejs.org/images/platform-icon-osx.png" width="45">
              Macintosh Installer
              <small>node-v0.10.26.pkg</small>

所以这里没有桌子。 希望这会有所帮助。

编辑: 我的代码如下以获得此响应:

def main():
    r = requests.get("http://nodejs.org/download/")
    soup = bs4.BeautifulSoup(r.text)
    # print r.text
    selector = "div.interior"
    print(soup.select(selector)[2])

编辑 2: 你可以用find试试。你对那个更灵活。

soup = bs4.BeautifulSoup(r.text)
print(soup.find("a", text="64-bit"))

编辑 3: 这应该有效:

def main():
    r = requests.get("http://nodejs.org/download/", headers={"content-type":"text", "User-   Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5"})
    soup = bs4.BeautifulSoup(r.text)
    print(soup.find("table").tr.td.findNextSibling().a['href'])

【讨论】:

  • WTF!有没有办法像普通浏览器一样解析html?
  • 编辑了回复。在请求中传递一个标头,你应该没问题。
猜你喜欢
  • 2018-10-04
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多