网页抓取 returns 为空
Web scraping returns empty
我第一次尝试学习抓取。我正在尝试获取 U.S 成员的正式名称。国会。
我成功地完成了 POST -- response.content
确实是完整的 html 字符串。但不知何故 lxml
和 bs4
并没有帮助我把名字说出来。
这是一个简短的示例,在 this site 上搜索姓氏 "Waxman"。我想要的结果是此人的全名,如 table 中所述。我做了 Inspect Element > copy XPATH on the name.
from lxml import html
import requests
shortname = 'WAXMAN'
state = 'California'
chamber = 'House'
url = 'http://bioguide.congress.gov/biosearch/biosearch1.asp'
formData = {'lastname': shortname}
response = requests.post(url, data=formData)
tree = html.fromstring(response.content)
print tree.xpath('/html/body/center/table/tbody/tr[1]/td[1]/a/text()')
我在 beautifulSoup 中的尝试也没有用,但我对那个包不太熟悉。
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.content, "lxml")
soup.select('body > center > table > tbody > tr:nth-child(2) > td:nth-child(1) > a')
您可以将表达式简化为:
//table//td/a/text()
正在打印 ['WAXMAN, Henry Arnold']
的结果。
我第一次尝试学习抓取。我正在尝试获取 U.S 成员的正式名称。国会。
我成功地完成了 POST -- response.content
确实是完整的 html 字符串。但不知何故 lxml
和 bs4
并没有帮助我把名字说出来。
这是一个简短的示例,在 this site 上搜索姓氏 "Waxman"。我想要的结果是此人的全名,如 table 中所述。我做了 Inspect Element > copy XPATH on the name.
from lxml import html
import requests
shortname = 'WAXMAN'
state = 'California'
chamber = 'House'
url = 'http://bioguide.congress.gov/biosearch/biosearch1.asp'
formData = {'lastname': shortname}
response = requests.post(url, data=formData)
tree = html.fromstring(response.content)
print tree.xpath('/html/body/center/table/tbody/tr[1]/td[1]/a/text()')
我在 beautifulSoup 中的尝试也没有用,但我对那个包不太熟悉。
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.content, "lxml")
soup.select('body > center > table > tbody > tr:nth-child(2) > td:nth-child(1) > a')
您可以将表达式简化为:
//table//td/a/text()
正在打印 ['WAXMAN, Henry Arnold']
的结果。