【发布时间】:2018-03-12 21:24:38
【问题描述】:
我使用 css 选择器在 python 中编写了一个脚本来解析网页中的一些姓名和电话号码。我创建的脚本没有给我预期的结果;相反,一些我不想要的信息也随之而来。如何纠正我的选择器,使其仅解析名称和电话号码,而不解析其他任何内容。为了您的考虑,我在底部粘贴了一个包含 html 元素的链接。提前致谢。
这是我写的:
from lxml.html import fromstring
root = fromstring(html)
for tree in root.cssselect(".cbFormTableEvenRow"):
try:
name = tree.cssselect(".cbFormDataCell span.cbFormData")[0].text
except:
name = ""
try:
phone = tree.cssselect(".cbFormLabel:contains('Phone Number')+td.cbFormDataCell .cbFormData")[0].text
except:
phone = ""
print(name,phone)
我期望的结果:
JAYMES CARTER (402)499-8846
我得到的结果:
1840390831
RESIDENTIAL
JAYMES CARTER (402)499-8846
None
My valuation jumped by almost $60,000 in one year. There are multiple comparable properties nearby that are much lower than my $194,300 evaluation, and a lot closer to my 2016 year evaluation of $134,400.
链接到html文件:
https://www.dropbox.com/s/64apg5cjpssd3hb/html_table.html?dl=0
【问题讨论】:
-
为什么不使用 xpath ?
标签: python python-3.x web-scraping css-selectors