1
Scrapyを使用してビジネスディレクトリをスクラブしていて、変数を使用してデータを抽出しようとする問題が発生しています。ここでは、コードは次のとおりです。Scrapyを使用して変数からテキストを抽出する方法は?
def parse_page(self, response):
url = response.meta.get('URL')
# Parse the locations area of the page
locations = response.css('address::text').extract()
# Takes the City and Province and removes unicode and removes whitespace,
# they are still together though.
city_province = locations[1].replace(u'\xa0', u' ').strip()
# List of all social links that the business has
social = response.css('.entry-content > div:nth-child(2) a::attr(href)').extract()
add_info = response.css('ul.list-border li').extract()
year = ""
for info in add_info:
if 'Year' in info:
year = info
else:
pass
yield {
'title': response.css('h1.entry-title::text').extract_first().strip(),
'description': response.css('p.mb-double::text').extract_first(),
'phone_number': response.css('div.mb-double ul li::text').extract_first(default="").strip(),
'email': response.css('div.mb-double ul li a::text').extract_first(default=""),
'address': locations[0].strip(),
'city': city_province.split(' ', 1)[0].replace(',', ''),
'province': city_province.split(' ', 1)[1].replace(',', '').strip(),
'zip_code': locations[2].strip(),
'website': response.css('.entry-content > div:nth-child(2) > ul:nth-child(2) > li:nth-child(1) > a:nth-child(1)::attr(href)').extract_first(default=''),
'facebook': response.css('.entry-content > div:nth-child(2) > ul:nth-child(2) > li:nth-child(2) > a:nth-child(1)::attr(href)').extract_first(default=''),
'twitter': response.css('.entry-content > div:nth-child(2) > ul:nth-child(2) > li:nth-child(3) > a:nth-child(1)::attr(href)').extract_first(default=''),
'linkedin': response.css('.entry-content > div:nth-child(2) > ul:nth-child(2) > li:nth-child(4) > a:nth-child(1)::attr(href)').extract_first(default=''),
'year': year,
'employees': response.css('.list-border > li:nth-child(2)::text').extract_first(default="").strip(),
'key_contact': response.css('.list-border > li:nth-child(3)::text').extract_first(default="").strip(),
'naics': response.css('.list-border > li:nth-child(4)::text').extract_first(default="").strip(),
'tags': response.css('ul.biz-tags li a::text').extract(),
}
私が午前問題はここからです。
add_info = response.css('ul.list-border li').extract()
year = ""
for info in add_info:
if 'Year' in info:
year = info
else:
pass
情報は「年設立」されている場合、コードのチェックを参照してください。ただし、HTMLを返します。私は今年を印刷するようにしようとしています。 add_info = response.css('ul.list-border li::text').extract()
年を印刷しますが、for
ループでこれを行うにはどうすればいいですか?
「年」がinfo
になるたびに、<li><span>Year Established:</span> 1998</li>
のように出力されます。私はちょうど年を取得し、HTMLを探していません。
迅速な対応に感謝します。しかし、私はJavaScriptで変数ではなく、すでに定義されているPython変数からテキストを抽出することを検討しています。私は現時点で得ている結果を示すために答えを更新しました。 – Lewis
「収穫期」はどうですか? – James
ごめんなさい@ブレンダン、私はあなたが何を意味するか分からない。 – Lewis