【发布时间】:2018-11-03 07:48:55
【问题描述】:
我想通过在 python 中使用 BeautifulSoup 和 Selenium 来练习使用真实世界的示例 (Airbnb) 进行抓取。具体来说,我的目标是获取洛杉矶内的所有房源(房屋)ID。我的策略是打开一个 chrome 并访问 Airbnb 网站,在那里我已经手动搜索了洛杉矶的房屋并从这里开始。在这个过程中,我决定使用硒。之后,我想解析源代码中的 HTML 代码,然后找到当前页面上显示的列表 ID。然后基本上,只想遍历所有页面。 这是我的代码:
from urllib import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver
option=webdriver.ChromeOptions()
option.add_argument("--incognito")
driver=webdriver.Chrome(executable_path="C:/Users/chromedriver.exe",chrome_options=option)
first_url="https://www.airbnb.com/s/Los-Angeles--CA--United-States/select_homes?refinement_paths%5B%5D=%2Fselect_homes&place_id=ChIJE9on3F3HwoAR9AhGJW_fL-I&children=0&guests=1&query=Los%20Angeles%2C%20CA%2C%20United%20States&click_referer=t%3ASEE_ALL%7Csid%3Afcf33cf1-61b8-41d5-bef1-fbc5d0570810%7Cst%3AHOME_GROUPING_SELECT_HOMES&superhost=false&title_type=SELECT_GROUPING&allow_override%5B%5D=&s_tag=tm-X8bVo"
n=3
for i in range(1,n+1):
if (i==1):
driver.get(first_url)
print first_url
#HTML parse using BS
html =driver.page_source
soup=BeautifulSoup(html,"html.parser")
listings=soup.findAll("div",{"class":"_f21qs6"})
#print out all the listing_ids within a current page
for i in range(len(listings)):
only_id= listings[i]['id']
print(only_id[8:])
after_first_url=first_url+"§ion_offset=%d" % i
print after_first_url
driver.get(after_first_url)
#HTML parse using BS
html =driver.page_source
soup=BeautifulSoup(html,"html.parser")
listings=soup.findAll("div",{"class":"_f21qs6"})
#print out all the listing_ids within a current page
for i in range(len(listings)):
only_id= listings[i]['id']
print(only_id[8:])
如果您发现任何效率低下的代码,请理解,因为我是初学者。我通过阅读和观看多个来源制作了这些代码。无论如何,我想我有正确的代码,但问题是每次我运行它时,我都会得到不同的结果。这意味着它在页面上循环,但有时它只给出一定数量的页面的结果。例如,它循环 page1 但不提供任何相应的输出,循环 page2 并提供结果但不为 page3 提供结果。它是如此随机,以至于它会为某些页面提供结果,但不会为某些其他页面提供结果。最重要的是,有时它会按顺序循环第 1、2、3、...,但有时它会循环第 1 页,然后移动到最后一页 (17),然后返回第 2 页。我想我的代码并不完美,因为它给出了不稳定的输出。有没有人有类似的经历或者有人可以帮我解决问题吗?谢谢。
【问题讨论】:
-
为什么你现在使用
selenium,而不是requests?那是因为 selenium 在 html 中提供了 javascript 创建的内容吗?有人可以在这里阐明一下吗?
标签: python html selenium beautifulsoup