【问题标题】:PyQuery won't return elements on a pagePyQuery 不会返回页面上的元素
【发布时间】:2019-08-11 22:48:14
【问题描述】:

我已经设置了一个 Python 脚本来使用PyQuery 打开这个网页。

import requests
from pyquery import PyQuery

url = "http://www.floridaleagueofcities.com/widgets/cityofficials?CityID=101"
page = requests.get(url)
pqPage = PyQuery(page.content)

但是pqPage("li") 只返回一个空白列表,[]。同时pqPage.text()显示页面的HTML文本,其中包含li元素。

为什么代码不会返回li 元素的列表?我如何让它做到这一点?

【问题讨论】:

  • 您是否尝试过查找过滤器来获取“li”元素?
  • @Vishal 是的。结果相同

标签: python python-3.x web-scraping pyquery


【解决方案1】:

似乎PyQuery 无法处理此页面 - 可能是因为它是xhtml 页面。或者可能是因为它使用命名空间xmlns="http://www.w3.org/1999/xhtml"

当我使用时

pqPage.css('li')

然后我得到

[<{http://www.w3.org/1999/xhtml}html#sfFrontendHtml>]

在元素中显示{http://www.w3.org/1999/xhtml} - 它是namespace。某些模块与使用命名空间的HTML 存在问题。


使用Beautifulsoup获取它没有问题

import requests
from bs4 import BeautifulSoup as BS

url = "http://www.floridaleagueofcities.com/widgets/cityofficials?CityID=101"
page = requests.get(url)

soup = BS(page.text, 'html.parser')
for item in soup.find_all('li'):
    print(item.text)

编辑:在谷歌中挖掘后,我发现在PyQuery() 中使用parser="html" 可以得到li

import requests
from pyquery import PyQuery

url = "http://www.floridaleagueofcities.com/widgets/cityofficials?CityID=101"
page = requests.get(url)

pqPage = PyQuery(page.text, parser="html")
for item in pqPage('li p'):
    print(item.text)

【讨论】:

  • BS4 解决方案有效。 PyQuery 可以解析这个页面吗?
  • 我发现使用parser="html"我可以得到它。请参阅答案中的新代码。
猜你喜欢
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 2020-08-16
相关资源
最近更新 更多