在本文中,我们将探讨如何使用 Python 来抓取 Google 的评论和评分数据。
所需模块:
- Beautiful Soup: 这里抓取的核心机制是解析 DOM,即从 HTML 和 XML 文件中提取数据。
# Installing with pip
pip install beautifulsoup4
# Installing with conda
conda install -c anaconda beautifulsoup4
- Scrapy:一个开源包,专门用于抓取大规模数据集,作为开源工具,它的使用效率很高。
- Selenium:通常,Selenium 用于自动化测试。我们也可以用它来进行抓取,因为浏览器自动化能帮助我们处理涉及 JavaScript 的交互,例如点击、滚动、多框架之间的数据传输等。
# Installing with pip
pip install selenium
# Installing with conda
conda install -c conda-forge selenium
Chrome driver manager:
# Below installations are needed as browsers
# are getting changed with different versions
pip install webdriver
pip install webdriver-manager
Web 驱动初始化:
Python3
CODEBLOCK_08bde797
输出:
> [WDM] – ====== WebDriver manager ======
>
>
> [WDM] – Current google-chrome version is 99.0.4844
>
>
> [WDM] – Get LATEST driver version for 99.0.4844
>
>
> [WDM] – Driver [C:\Users\ksaty\.wdm\drivers\chromedriver\win32\99.0.4844.51\chromedriver.exe] found in cache
让我们尝试定位“总统府”,然后进行后续操作。如果是第一次操作,有时它会请求访问页面的权限。如果遇到权限问题,只需同意并继续即可。
Python3
CODEBLOCK_8f8c6ab4
输出:
> https://www.google.com/maps/place/Rashtrapati+Bhavan/@28.6143478,77.1972413,17z/data=!3m1!4b1!4m5!3m4!1s0x390ce2a99b6f9fa7:0x83a25e55f0af1c82!8m2!3d28.6143478!4d77.19943
在这里,我们将尝试从 Google 地图上获取三类实体,比如书店、食物和寺庙。为此,我们将设置特定的条件,并将它们与位置信息合并。
Python3
CODEBLOCK_6842d208
输出: