文本=响应.textAttributeError:“unicode”对象没有属性“text”

2024-04-20 00:03:11 发布

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

我使用parse方法在本地保存一些html文件,然后我想解析它们。但我得到了AttributeError: 'unicode' object has no attribute 'text'

我知道我可以将这个过程分成两个方法,这意味着首先我保存这些html文件,然后再传递给另一个方法并解析它们。但我需要用相同的方法保存和解析。在

这是我的密码

def parse(self, response):

    sel = Selector(response)
    company = CompanyItem()     

    total_results_count = self.driver.find_element_by_xpath("//div[@class='totalResultsCount big']").text
    if total_results_count >3:
        person_1 = WebDriverWait(self.driver,10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "tr:nth-child(1) > td.personName > a")))
        person_1.click()

        person_profile = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located((By.ID, "profileSectionContent")))
        html_source = self.driver.find_element_by_xpath("//table[@id='personSummaryTable']").get_attribute("outerHTML")
        f = open('person_1_%s.html'%(company['c_name']), 'w')
        f.write(html_source.encode('utf-8'))
        f.close()
        person_path = 'file:///Users/cengcengruihong/Desktop/scrapy_learning/zoominfo_test/' + 'person_1_%s.html'%(company['c_name'])
        cookies = self.driver.get_cookies()

        sel = HtmlXPathSelector(person_path)
        company['p1c_name'] = sel.xpath("//h1[@itemprop='name']/text()").extract_first().strip("\n")
        company['p1c_role'] = sel.xpath("//h2[@itemprop='role']/text()").extract_first().strip("\n")
        company['p1c_phoneNumber'] = sel.xpath("//div[@class='phoneNumber']/text()[position()=2]").extract_first().strip("\n")
        company['p1c_email'] = sel.xpath("//span[@class='personEmail']/a/text()").extract_first().strip()

        yield company

有人给我一个暗示将不胜感激。谢谢


Tags: 方法textnameselfhtmldriverextractelement
2条回答

使用这段代码可以使用Scrapy解析HTML。在

from scrapy.http import HtmlResponse
response = HtmlResponse(url="", body='<div id="test">Test text</div>')
response.xpath('//div[@id="test"]/text()').extract()[0].strip()

您可以读取文件的内容,然后将其传递给body参数。在

你的问题来了

person_path = 'file:///Users/cengcengruihong/Desktop/scrapy_learning/zoominfo_test/' + 'person_1_%s.html'%(company['c_name'])
    cookies = self.driver.get_cookies()

    sel = HtmlXPathSelector(person_path)

当选择器的构造函数需要Response对象作为第一个参数时,可以将文件名传递给它的构造函数。要从文件内容创建选择器,应执行以下操作:

^{pr2}$

相关问题 更多 >