我使用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如果有人给我一个提示,我将不胜感激。谢谢
发布于 2017-01-22 20:52:58
你的问题在这里
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)将filename传递给选择器的构造函数,而选择器的构造函数期望Response对象作为第一个参数。要从文件内容创建选择器,您应该这样做:
from scrapy.selector import Selector
with open(person_path) as fp:
sel = Selector(text=fp.read())发布于 2017-01-22 20:52:39
使用此代码可以使用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参数。
https://stackoverflow.com/questions/41791013
复制相似问题