Python中的Web抓取表数据
我试图从一个网页上抓取一个数据表,我在网上找到的所有教程都太具体了,没有解释每个参数/元素是什么,所以我不知道如何在我的示例中使用它。任何关于在哪里找到好的教程来获取此类数据的建议都将不胜感激Python中的Web抓取表数据,python,web-scraping,Python,Web Scraping,我试图从一个网页上抓取一个数据表,我在网上找到的所有教程都太具体了,没有解释每个参数/元素是什么,所以我不知道如何在我的示例中使用它。任何关于在哪里找到好的教程来获取此类数据的建议都将不胜感激 query = urllib.urlencode({'q': company}) page = requests.get('http://www.hoovers.com/company-information/company-search.html?term=company') tree = html.f
query = urllib.urlencode({'q': company})
page = requests.get('http://www.hoovers.com/company-information/company-search.html?term=company')
tree = html.fromstring(page.text)
table =tree.xpath('//[@id="shell"]/div/div/div[2]/div[5]/div[1]/div/div[1]')
#Can't get xpath correct
#This will create a list of companies:
companies = tree.xpath('//...')
#This will create a list of locations
locations = tree.xpath('//....')
我也尝试过:
hoover = 'http://www.hoovers.com/company-information/company-search.html?term=company'
req = urllib2.Request(hoover)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
table = soup.find("table", { "class" : "clear data-table sortable-header dashed-table-tr alternate-rows" })
f = open('output.csv', 'w')
for row in table.findAll('tr'):
f.write(','.join(''.join([str(i).replace(',','') for i in row.findAll('td',text=True) if i[0]!='&']).split('\n')[1;-1])+'\n')
f.close()
但是最后一行的第二行出现了无效的语法错误是的,漂亮的汤。下面是一个快速获取名称的示例:
hoover = 'http://www.hoovers.com/company-information/company-search.html?term=company'
req = urllib2.Request(hoover)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page.text)
trs = soup.find("div", attrs={"class": "clear data-table sortable-header dashed-table-tr alternate-rows"}).find("table").findAll("tr")
for tr in trs:
tds = tr.findAll("td")
if len(tds) < 1:
continue
name = tds[0].text
print name
f.close()
胡佛http://www.hoovers.com/company-information/company-search.html?term=company'
req=urllib2.请求(胡佛)
page=urlib2.urlopen(请求)
soup=BeautifulSoup(page.text)
trs=soup.find(“div”,attrs={“class”:“clear data table sortable header虚线表tr alternate rows”}.find(“table”).findAll(“tr”)
对于trs中的tr:
tds=tr.findAll(“td”)
如果len(tds)<1:
持续
name=tds[0]。文本
印刷品名称
f、 关闭()
谢谢!非常有帮助,但我正试图以这种方式编写页面源代码,而不是在html页面中读取,因为目的是将其构建到一个函数中:hoovers=''req=urllib2.Request(hoovers)page=urllib2.urlopen(req)soup=BeautifulSoup(page),但是当我运行解决方案的第三行时,我得到了一个attribute错误,表没有属性find!BeautifulSoup构造函数接受流或字符串,因此您应该能够传递page.text或流版本。抱歉,我不明白您所说的传递page.text或流版本是什么意思?在上面的示例中,您调用的是返回web请求内容字符串的page.text。这应该足以调用BeautifulSoup构造函数。所以,我认为您需要的是soup=beautifulsou(page.text)。我不熟悉您如何使用urllib,因此我只能针对示例的page.text部分发言。如果你能提供更多的代码,我可以试试。