python-使用beautifulsoup4的CSS选择不起作用
作者:互联网
我尝试了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()
解决方法:
此页面上的答案不同于在浏览器中查看与使用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'])
标签:beautifulsoup,web-scraping,python 来源: https://codeday.me/bug/20191121/2055704.html