从表中提取(草皮)

时间:2018-08-03 07:51:18

标签: python html xpath scrapy

想在python2中使用scrapy寻求表解析方面的帮助 这是我的桌子: link to table 我需要获取<td>标签的值。 尝试使用下一个python代码:

rows = resp.xpath('//*[@id="Vorlage_Infobox_Unternehmen"]')
if not rows:
    rows = resp.xpath('.//*[@id="Vorlage_Infobox_Unternehmen"]//table')
try:
    if rows:
        extract = lambda row, path: row.xpath(path).extract_first().strip()
        if '<th>' in str(rows):
            infobox = {extract(row, 'string(./th)'): extract(row, 'string(./td)') for row in rows}
        elif '<tr>' in str(rows):
            infobox = {extract(row, 'string(./td[1])'): extract(row, 'string(./td[2])') for row in rows}
        elif '<table>' in str(rows):
            infobox = {extract(row, 'string(./th)'): extract(row, 'string(./td)') for row in rows}
        else:
            infobox = {extract(row, 'string(./table/tbody/tr[1])'): extract(row, 'string(./td[1])') for row in rows}

但是我做错了事,无法得到我的魔杖。请帮助我理解我的错误。

1 个答案:

答案 0 :(得分:0)

如果要获取<td><table>的值,可以在xpath上执行此操作:

    table = resp.xpath('//table[@id="Vorlage_Infobox_Unternehmen"]')
    if table:
        all_table_data = table.xpath('//td')

在使用table.xpath('some_xpath')时,它将应用于已选择的元素。您也可以跳过该测试并直接进行:

    all_table_data = resp.xpath('//table[@id="Vorlage_Infobox_Unternehmen"]//td')