gpt4 book ai didi

python - 如何使用scrapy在Python中抓取url

转载 作者:行者123 更新时间:2023-12-01 04:02:13 35 4
gpt4 key购买 nike

我想使用 python 中的 scrapy 从特定网站提取 URL,该网站具有以下 HTML 结构

<div class="comic-table">
<div id="comic">
<img src="http://demowebsite.com/uploads/image1" alt="" title="">
<img src="http://demowebsite.com/uploads/image2" alt="" title="">
</div>
</div>

这是我编写的scrapy代码:

import scrapy
from scrapy.contrib.spiders import Rule, CrawlSpider
from scrapy.contrib.linkextractors import LinkExtractor
from Pencils.items import PencilsItem

class Spider(CrawlSpider):
name = 'pencil'
allowed_domains = ['demowebsite.com']
start_urls = ['http://demowebsite.com']
rules = [Rule(LinkExtractor(allow=['/uploads/.*']), 'parse_pencil')]

def parse_pencil(self, response):

image = PencilsItem()
rel = response.xpath("WHAT_SHOULD_I_PUT_HERE").extract()
image['image_urls'] = ['http:'+rel[0]]
return image

我应该在response.xpath字段中放入什么内容。

P.S 我是 HTML 和 Python 的初学者

最佳答案

试试这个:

    '//div[@id="comic"]/img'

// => search the whole html page
@ => attribute

xpath 会查找所有 <div>具有名为 id 的属性的标签等于 "comic" (应该只有一个带有属性 <div>id="comic" 标记,因为 id 应该是唯一的),并提取 <img>其中的标签。

使用 scrapy,您可以执行类似以下操作来获取所有 <img>标签:

import scrapy

class TestSpider(scrapy.Spider):
name = "my_spider"

start_urls = [
"file:///Users/7stud/python_programs/scrapy_stuff/html_files/html.html"
]

def parse(self, response):
for selector in response.xpath('//div[@id="comic"]/img'):
src = selector.xpath('@src').extract()
print src[0]



--output:--
(scrapy_env)~/python_programs/scrapy_stuff$ scrapy crawl my_spider
2016-03-29 02:19:09 [scrapy] INFO: Scrapy 1.0.5 started (bot: scrapy_stuff)
2016-03-29 02:19:09 [scrapy] INFO: Optional features available: ssl, http11
2016-03-29 02:19:09 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'scrapy_stuff.spiders', 'SPIDER_MODULES': ['scrapy_stuff.spiders'], 'BOT_NAME': 'scrapy_stuff'}
2016-03-29 02:19:09 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, LogStats, CoreStats, SpiderState
2016-03-29 02:19:09 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2016-03-29 02:19:09 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2016-03-29 02:19:09 [scrapy] INFO: Enabled item pipelines:
2016-03-29 02:19:09 [scrapy] INFO: Spider opened
2016-03-29 02:19:09 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-03-29 02:19:09 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2016-03-29 02:19:09 [scrapy] DEBUG: Crawled (200) <GET file:///Users/7stud/python_programs/scrapy_stuff/html_files/html.html> (referer: None)
http://demowebsite.com/uploads/image1
http://demowebsite.com/uploads/image2
2016-03-29 02:19:09 [scrapy] INFO: Closing spider (finished)
2016-03-29 02:19:09 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 263,
'downloader/request_count': 1,
'downloader/request_method_count/GET': 1,
'downloader/response_bytes': 243,
'downloader/response_count': 1,
'downloader/response_status_count/200': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2016, 3, 29, 8, 19, 9, 251971),
'log_count/DEBUG': 2,
'log_count/INFO': 7,
'response_received_count': 1,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2016, 3, 29, 8, 19, 9, 139531)}
2016-03-29 02:19:09 [scrapy] INFO: Spider closed (finished)
(scrapy_env)~/python_programs/scrapy_stuff$

事实上,如果您想要的只是 <img> 中的 src 属性标签,您可以使用以下xpath直接获取src属性:

def parse(self, response):
for selector in response.xpath('//div[@id="comic"]/img/@src'):
print selector.extract()

--output:--
...
2016-03-29 02:33:56 [scrapy] DEBUG: Crawled (200) <GET file:///Users/7stud/python_programs/scrapy_stuff/html_files/html.html> (referer: None)
http://demowebsite.com/uploads/image1
http://demowebsite.com/uploads/image2
2016-03-29 02:33:57 [scrapy] INFO: Closing spider (finished)
...

P.S I'm a beginner in HTML and Python

xml 和 xpath 怎么样?您真正需要探索的主题是 xpath。但是,我建议作为 html 和 xpath 的初学者,您应该从 BeautifulSoup 开始抓取网页。

关于python - 如何使用scrapy在Python中抓取url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36276633/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com