【问题标题】:Scraping Javascript Text with Python and Selenium使用 Python 和 Selenium 抓取 Javascript 文本
【发布时间】:2017-03-26 00:03:45
【问题描述】:

我正在尝试从 TripAdvisor 餐厅获取纬度和经度。该信息没有在网页上突出显示,但我确实在 HTML 中找到了它:

Latitude and Longitude w/in Javascript

我正在尝试使用此代码提取所有信息:

#import libraries
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

for i in range(0, 30, 30):
    #need this here for when you want more than 30
    while i <= range:
        i = str(i)
        #url format offsets the restaurants in increments of 30 after the oa
        url1 = 'https://www.tripadvisor.com/Restaurants-g294217-oa' + i + '-Hong_Kong.html#EATERY_LIST_CONTENTS'
        r1 = requests.get(url1)
        data1 = r1.text
        soup1 = BeautifulSoup(data1, "html.parser")
        for link in soup1.findAll('a', {'property_title'}):
            #print 'https://www.tripadvisor.com/Restaurant_Review-g294217-' + link.get('href')
            restaurant_url = 'https://www.tripadvisor.com/Restaurant_Review-g294217-' + link.get('href')
            browser = webdriver.Chrome('C:\Python27\Chromedriver\chromedriver.exe')
            # use xpath to get to the information in the JS
            print browser.find_element_by_xpath("""/html/body/script[22]""")

当我运行代码时,它告诉我它无法找到该元素。也许我现在有点脑死亡,但如果有一双新的眼睛可以看看这个,让我知道我是否做错了,或者如果有不同的方法可以解决这个问题,我会全神贯注。

【问题讨论】:

  • 不确定您的问题,但while i &lt;= range: 无效,因为range 是一个函数。
  • 谢谢,我会调查的。如果您查看我发布的图片的链接。我正试图从那张照片中提取这些信息。但是当我运行它时,它告诉我代码无法在 xpath 中找到该元素。

标签: javascript python python-2.7 selenium web-scraping


【解决方案1】:

当您使用selenium webdriver 时,使用requestsBeautifulSoup 包没有意义,因为 selenium 可以打开网页(requests) 并自行获取内容(BeautifulSoup)。以下是您尝试使用 selenium 完成的粗略结构。

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys


browser = webdriver.Chrome('C:\Python27\Chromedriver\chromedriver.exe')
for counter in range(0, 30, 30):
    #need this here for when you want more than 30
    while i <= counter:
        i = str(i)
        url1 = 'https://www.tripadvisor.com/Restaurants-g294217-oa' + i + '-Hong_Kong.html#EATERY_LIST_CONTENTS'
        browser.get(url1) # this will redirect to webpage
        # use xpath to get to the information in the JS
        print browser.find_element_by_xpath("""/html/body/script[22]""")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-22
    • 2013-01-09
    • 2020-12-29
    • 2020-01-10
    • 2022-12-22
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    相关资源
    最近更新 更多