私は現在スクレイピーを試しています。特定の Web ページからいくつかのリンクをスクレイピングし、それらを xml ファイルにエクスポートしています。問題は次のとおりです。特定のサイトの場合、リンクに完全な URL が含まれていません (例: example.com/page/abc スクレイピングされたリンクは、スクレイピングされたページからの相対パス (例: page/abc) にすぎません)。スクレイピングされた変数にベース URL を追加したいと思います。
item['link'] = link.select('a/@href').extract() would become something like:
item['link'] = "http://example.com" + link.select('a/@href').extract()
したがって、結果は完全に使用可能な URL になりますが、上記の解決策は機能しません (文字列が追加されると注意がスクレイピングされます。できれば、スクレイピーで完全な URL を自動的にスクレイピングしたいと思います。
私はPythonに慣れていないので、解決策は非常に簡単ですが、いくつか読んだ後、Scrapyが推奨されるスパイダーでした.
何か問題はありますか?
現在のコード:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from tutorial.items import MyItem
class MySpider(BaseSpider):
name = "example-com"
allowed_domains = ["http://example.com"]
start_urls = [
"http://example.com/page.html",
]
def parse(self, response):
hxs = HtmlXPathSelector(response)
links = hxs.select('//div[@class="views-field views-field-title"]')
items = []
for link in links:
item = MyItem()
item['link'] = link.select('span/a/@href').extract()
items.append(item)
for item in items:
yield item
更新/追加の質問
スクレイピングされたアイテムの数、スパイダーが実行された日付、ドメイン名やスパイダー名など、より多くの情報を xml ファイルに入れることもできますか? さらに変数を返そうとしましたが、うまくいきませんでした。