Xpath在浏览器和刮擦中给出不同的结果



我试图从这个网站上抓取python课程信息: https://www.udemy.com/topic/python/。

我写了一个 xpath 来选择标题文本:

/

/div[@data-purpose='course-card-title']/text((

当我在 chrome 上测试它时,这有效,它给出了 39 个匹配项,但我在 scrapy 上得到了一个空列表。

正如Tarun Lalwani的评论中提到的,您在浏览器中看到的数据是使用Javascript创建的。一种方法可能是使用Selenium或Scrapy飞溅,另一种方法是找到所做的API调用并直接使用它们。

使用浏览器的DevTools(ctrl + shift + c(并检查"网络"选项卡。查看重新加载页面后会发生什么。您应该注意到,有人向他们的 API 发出请求,您可以使用和操纵这些请求来获取您要查找的数据。从 json 格式的响应中,您可以提取要查找的数据。

下面是一个最小的工作示例,用于打印您在 https://www.udemy.com/topic/python/顶部看到的课程标题:

import scrapy
import json

class UdemySpider(scrapy.Spider):
name = "udemy"
start_urls = ['https://www.udemy.com/api-2.0/discovery-units/?context=topic&from=0&page_size=10&item_count=12&excluded_course_ids=&label_id=7380&source_page=topic_page&locale=de_DE&currency=eur&navigation_locale=en_US&skip_price=true']
def parse(self, response):
jsonresponse = json.loads(response.body_as_unicode())
for item in jsonresponse['units'][0]['items']:
print(item['title'])

打印结果(至少对于来自德国的用户(将如下所示:

Python Bootcamp: Vom Anfänger zum Profi, inkl. Data Science
Python für Data Science, Machine Learning & Visualization
Data Science & Maschinelles Lernen in Python - am Beispiel
Machine Learning Komplettkurs mit Python inkl. AI Einführung
Python Bootcamp: Der Einstiegskurs
Python - Das Python Grundlagen Bootcamp - Von 0 auf 100!
Visualisiere Daten mit Python - auch für Anfänger!
Data Science, Apache Spark & Python: Analysiere echte Daten!
Fortgeschrittene Python Programmierung
Complete Python Bootcamp: Go from zero to hero in Python 3
Machine Learning A-Z™: Hands-On Python & R In Data Science
Python for Data Science and Machine Learning Bootcamp

最新更新