如何同时选择头部和身体标签

2024-03-28 10:12:32 发布

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

所以,我有一个爬虫,它需要从头部的meta标记和身体中的一些元素标记中提取一些数据。在

当我尝试这个的时候

for courses in response.xpath("//html"):

还有这个

for courses in response.xpath("//head"):

它只从<head>... </head>标记中的meta标记获取数据。在

当我尝试这个的时候

for courses in response.xpath("//body"):

它只从html<body>... </body>标记内的标记获取数据。在

如何组合这两个选择器,我也试过了

for courses in response.xpath("//head | //body"):

但它只从<head>... </head>返回'meta'标记,没有从body中提取任何内容。在

我也试过这个

for courses in response.xpath("//*"):

它是有效的,但这是非常低效的,需要大量的时间来提取。我相信有一种更有效的方法来做这件事。在

如果有用的话,这里有一些垃圾代码…

yeld下的前2个元素(pagetype,pagefeatured)在<head> ... <head>标记中。最后两个元素(coursetloc,coursetfees)在<body ... </body>标记中

是的,这可能看起来很奇怪,但在我正在抓取的网站<body>...</body>内有“meta”标记。

class MySpider(BaseSpider):
name = "dkcourses"
start_urls = ['http://www.example.com/scrapy/all-courses-listing']
allowed_domains = ["example.com"]
def parse(self, response):
 hxs = Selector(response)
 for courses in response.xpath("//body"):
 yield {
            'pagetype': ''.join(courses.xpath('.//meta[@name="dkpagetype"]/@content').extract()),
            'pagefeatured': ''.join(courses.xpath('.//meta[@name="dkpagefeatured"]/@content').extract()),
            'coursetloc': ''.join(courses.xpath('.//meta[@name="dkcoursetloc"]/@content').extract()),
            'coursetfees': ''.join(courses.xpath('.//meta[@name="dkcoursetfees"]/@content').extract()),
           }
 for url in hxs.xpath('//ul[@class="scrapy"]/li/a/@href').extract()):
  yield Request(response.urljoin(url), callback=self.parse)

非常感谢任何帮助。谢谢


Tags: namein标记元素forresponsehtmlextract
1条回答
网友
1楼 · 发布于 2024-03-28 10:12:32
  1. 使用extract_first()获取extract()中的第一个值,不要使用join()
  2. 使用[starts-with(@name, "dkn")]查找meta标记,//meta表示文档的所有内容。在

In [5]: for meta in response.xpath('//meta[starts-with(@name, "dkn")]'):
   ...:     name = meta.xpath('@name').extract_first()
   ...:     content = meta.xpath('@content').extract_first()
   ...:     print({name:content})

输出:

^{pr2}$

相关问题 更多 >