1

我正在使用 selenium 和 scrapy 导航到数据表,我想将链接/href 提取到 csv 文件。到目前为止,我尝试过的一切似乎都不起作用,我不确定要尝试什么或如何获取链接。

这是我试图从中提取链接/href 的表的重要部分:

<tr class="even">

<td class="paddingColumnValue"> </td>

<td class="nameColumnValue"><a href="/m/app?service=external/sdata_details&sp=12812" class="sdata" title="Click here for additional details.">click</a></td>

<td class="amountColumnValue">$600,000.00</td>

<td class="myListColumnValue"><a href="" onclick="doMyListButton(this.firstChild.getAttribute('src'),this.name);myListHandler(this.name);return false;"  önmouseover="return true" name="12812"><img src="/m/images/add.gif" border="0" title="Click to add this to your list" name="A12812"></a></td>


</tr>

我最接近实际获取数据的是使用此代码...(注意表 id = search_results)

import time
from scrapy.item import Item, Field
from selenium import webdriver
from scrapy.spider import BaseSpider
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector

class ElyseAvenueItem(Item):
    link = Field()

class ElyseAvenueSpider(BaseSpider):
    name = "elyse"
    allowed_domains = ["domain.com"]
    start_urls = [
'http://www.domain.com']

def __init__(self):
    self.driver = webdriver.Firefox()

def parse(self, response):
    self.driver.get(response.url)
    el1 = self.driver.find_element_by_xpath("//*[@id='headerRelatedLinks']/ul/li[5]/a")
    el1.click()
    time.sleep(2)
    el2 = self.driver.find_element_by_xpath("/html/body/form/table/tbody/tr[2]/td[2]/table/tbody/tr/td[3]/p[3]/a[1]")
    if el2:
        el2.click()
        time.sleep(2)
    el3 = self.driver.find_element_by_xpath("/html/body/form/table/tbody/tr[2]/td[2]/table[1]/tbody/tr/td[3]/a")
    if el3:
        el3.click()
        time.sleep(20)


        titles = self.driver.find_elements_by_class_name("sdata")
        items = []
        for titles in titles:
            item = ElyseAvenueItem()
            item ["link"] = titles.find_element_by_xpath("//*[@id='search_results']/tbody/tr[2]/td[2]/a")
            items.append(item)
            return item

输出到 csv:selenium.webdriver.remote.webelement.WebElement 对象位于 0x03F16E90

感谢您的帮助。如果有帮助,我可以发布更多我的尝试和他们的输出。就像我说的,我需要的是 href,我只是不知道该怎么做。

4

1 回答 1

1

You are scraping selenium webelement instance instead of it's text. Replace:

item ["link"] = titles.find_element_by_xpath("//*[@id='search_results']/tbody/tr[2]/td[2]/a")

with

link = titles.find_element_by_xpath("//*[@id='search_results']/tbody/tr[2]/td[2]/a")
item ["link"] = link.get_attribute('href')

Hope that helps.

于 2013-07-25T21:39:52.997 回答