Skip to main content
 首页 » 编程设计

python之用 Beautifulsoup-Python 抓取

2024年10月01日10Free-Thinker

我想在酒店的每个评论页面中抓取 tripadvisor 中的酒店名称。

我用python写了一段代码,很简单,我觉得不假。

但每次它都停在不同的点(例如页面第一次停在第 150 页,第二次停在第 330 页)。

我 100% 确信我的代码是正确的。有没有可能是tripadvisor每次都屏蔽我?

我更新了代码,我也使用了 selenium,但问题仍然存在

更新后的代码如下:

from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.common.exceptions import TimeoutException 
from selenium.common.exceptions import NoSuchElementException 
from bs4 import BeautifulSoup 
import os 
import urllib.request 
import time 
import re 
 
file2 = open(os.path.expanduser(r"~/Desktop/TripAdviser Reviews2.csv"), "wb") 
 
file2.write(b"hotel,Address,HelpCount,HotelCount,Reviewer" + b"\n") 
 
Checker ="REVIEWS" 
 
# example option: add 'incognito' command line arg to options 
option = webdriver.ChromeOptions() 
option.add_argument("--incognito") 
 
# create new instance of chrome in incognito mode 
browser = webdriver.Chrome(executable_path='/Users/thimios/AppData/Local/Google/chromedriver.exe', chrome_options=option) 
#print(browser) 
 
 
# go to website of interest 
for i in range(10,50,10): 
    Websites=["https://www.tripadvisor.ca/Hotel_Review-g190479-d3587956-Reviews-or"+str(i)+"-The_Thief-Oslo_Eastern_Norway.html#REVIEWS"] 
    print(Websites) 
    for theurl in Websites: 
        thepage=browser.get(theurl) 
        thepage1 = urllib.request.urlopen(theurl) 
        soup = BeautifulSoup(thepage1, "html.parser") 
        # wait up to 10 seconds for page to load 
        timeout = 5 
        try: 
            WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="HEADING"]'))) 
            #print(WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="HEADING"]')))) 
        except TimeoutException: 
            print("Timed out waiting for page to load") 
            browser.quit() 
 
 
        # Extract the helpful votes, hotel reviews 
        helpcountarray = "" 
        hotelreviewsarray = "" 
 
        for profile in soup.findAll(attrs={"class": "memberBadging g10n"}): 
            image = profile.text.replace("\n", "|||||").strip() 
            #print(image) 
 
            if image.find("helpful vote") > 0: 
                counter = re.findall('\d+', image.split("helpful vote", 1)[0].strip()[-4:]) 
                if len(helpcountarray) == 0: 
                    helpcountarray = [counter] 
                else: 
                    helpcountarray.append(counter) 
            elif image.find("helpful vote") < 0: 
                if len(helpcountarray) == 0: 
                    helpcountarray = ["0"] 
                else: 
                    helpcountarray.append("0") 
            print(helpcountarray) 
            #print(len(helpcountarray)) 
 
            if image.find("hotel reviews") > 0: 
                counter = re.findall('\d+', image.split("hotel reviews", 1)[0].strip()[-4:]) 
                if len(hotelreviewsarray) == 0: 
                    hotelreviewsarray = counter 
                else: 
                    hotelreviewsarray.append(counter) 
            elif image.find("hotel reviews") < 0: 
                if len(hotelreviewsarray) == 0: 
                    hotelreviewsarray = ['0'] 
                else: 
                    hotelreviewsarray.append("0") 
            print(hotelreviewsarray) 
            #print(len(hotelreviewsarray)) 
 
 
        hotel_element = browser.find_elements_by_xpath('//*[@id="HEADING"]') 
        Address_element = browser.find_elements_by_xpath('//*[@id="HEADING_GROUP"]/div/div[3]/address/div/div[1]') 
 
        for i in range(0,10): 
            print(i) 
            for x in hotel_element: 
                hotel = x.text 
                print(hotel) 
                #print(type(hotel)) 
            for y in Address_element: 
                Address = y.text.replace(',', '').replace('\n', '').strip() 
                print(Address) 
                #print(type(Address)) 
 
            HelpCount = helpcountarray[i] 
            HelpCount = " ".join(str(w) for w in HelpCount) 
            print(HelpCount) 
            #print(type(HelpCount)) 
            HotelCount = hotelreviewsarray[i] 
            HotelCount = " ".join(str(w) for w in HotelCount) 
            print(HotelCount) 
            #print(type(HotelCount)) 
            Reviewer = soup.findAll(attrs={"class": "username mo"})[i].text.replace(',', ' ').replace('”', '').replace('“', '').replace('"', '').strip() 
            print(Reviewer) 
 
 
            Record2 = hotel + "," + Address +"," + HelpCount +"," + HotelCount+"," +Reviewer 
 
            if Checker == "REVIEWS": 
                file2.write(bytes(Record2, encoding="ascii", errors='ignore') + b"\n") 
 
 
file2.close() 

我在某处读到我应该添加标题。有点像

headers={'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'} 

为了网站允许我抓取它。是真的吗?

谢谢你的帮助

请您参考如下方法:

是的。有这样的可能。

网站用于防止网络抓取,例如检测和禁止机器人抓取(查看)他们的页面。

默认的 User-Agent 通常是指使用 python 软件实现的自动化流程,因此您需要将其更改为类似 User-Agent 的浏览器。

尽管如此,我不认为您被 TripAdvisor 屏蔽了。