刮板wiki+lxml。如何获取具有类的元素的子元素的href属性?

2024-06-07 14:59:15 发布

您现在位置:Python中文网/ 问答频道 /正文

在URL中包含“alpha”的链接上有许多链接(href),我希望从20个不同的页面收集这些链接并粘贴到常规URL的末尾(最后一行第二行)。href位于一个表中,该表的类是td的mys elastic mys,a显然是包含href属性的元素。任何帮助都将非常感谢,因为我已经在这个工作了大约一个星期。

for i in range(1, 11):
# The HTML Scraper for the 20 pages that list all the exhibitors
 url = 'http://ahr13.mapyourshow.com/5_0/exhibitor_results.cfm?alpha=%40&type=alpha&page='         + str(i) + '#GotoResults'
print url
list_html = scraperwiki.scrape(url)
root = lxml.html.fromstring(list_html)
href_element = root.cssselect('td.mys-elastic mys-left a')

for element in href_element:
#   Convert HTMl to lxml Object 
 href = href_element.get('href')
 print href

 page_html = scraperwiki.scrape('http://ahr13.mapyourshow.com' + href)
 print page_html

Tags: inalphaurlfor链接htmlpageelement
2条回答
import lxml.html as lh
from itertools import chain

URL = 'http://ahr13.mapyourshow.com/5_0/exhibitor_results.cfm?alpha=%40&type=alpha&page='
BASE = 'http://ahr13.mapyourshow.com'
path = '//table[2]//td[@class="mys-elastic mys-left"]//@href'

results = []   
for i in range(1,21):     
    doc=lh.parse(URL+str(i)) 
    results.append(BASE+i for i in doc.xpath(path))

print list(chain(*results))

不需要在javascript上浪费时间-它都在html中:

import scraperwiki
import lxml.html

html = scraperwiki.scrape('http://ahr13.mapyourshow.com/5_0/exhibitor_results.cfm?  alpha=%40&type=alpha&page=1')

root = lxml.html.fromstring(html)
# get the links
hrefs = root.xpath('//td[@class="mys-elastic mys-left"]/a')

for href in hrefs:
   print 'http://ahr13.mapyourshow.com' + href.attrib['href'] 

相关问题 更多 >

    热门问题