Reputation: 67
I am trying to scrape a table of data from a web page, all the tutorials I have found online are too specific and don't explain what each argument/element is so I can't figure out how to work it for my example. Any advice on where to find good tutorials to scrape this kind of data would be appreciated;
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('//....')
I have also tried:
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()
But I am getting an invalid syntax error on the second last line
Upvotes: 3
Views: 2256
Reputation: 137
Yes, beautiful soup. Here is a quick example to get the names:
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()
Upvotes: 3