【发布时间】:2019-09-28 19:16:44
【问题描述】:
我正在尝试抓取 Backcountry.com 的评论部分。该站点使用动态加载更多部分,即当您想要加载更多评论时,网址不会改变。我正在使用 Selenium webdriver 与加载更多评论的按钮和 BeautifulSoup 进行交互以抓取评论。
我能够成功地与加载更多按钮交互并加载所有可用评论。在您尝试加载更多按钮之前,我还能够抓取出现的初始评论。
总结:我可以与加载更多按钮交互,我可以抓取可用的初始评论,但我无法在加载所有评论后抓取所有可用评论。
我已尝试更改 html 标记,看看是否会有所不同。我试图增加睡眠时间,以防刮板没有足够的时间来完成它的工作。
# URL and Request code for BeautifulSoup
url_filter_bc = 'https://www.backcountry.com/msr-miniworks-ex-ceramic-water-filter?skid=CAS0479-CE-ONSI&ti=U2VhcmNoIFJlc3VsdHM6bXNyOjE6MTE6bXNy'
res_filter_bc = requests.get(url_filter_bc, headers = {'User-agent' : 'notbot'})
# Function that scrapes the reivews
def scrape_bc(request, website):
newlist = []
soup = BeautifulSoup(request.content, 'lxml')
newsoup = soup.find('div', {'id': 'the-wall'})
reviews = newsoup.find('section', {'id': 'wall-content'})
for row in reviews.find_all('section', {'class': 'upc-single user-content-review review'}):
newdict = {}
newdict['review'] = row.find('p', {'class': 'user-content__body description'}).text
newdict['title'] = row.find('h3', {'class': 'user-content__title upc-title'}).text
newdict['website'] = website
newlist.append(newdict)
df = pd.DataFrame(newlist)
return df
# function that uses Selenium and combines that with the scraper function to output a pandas Dataframe
def full_bc(url, website):
driver = connect_to_page(url, headless=False)
request = requests.get(url, headers = {'User-agent' : 'notbot'})
time.sleep(5)
full_df = pd.DataFrame()
while True:
try:
loadMoreButton = driver.find_element_by_xpath("//a[@class='btn js-load-more-btn btn-secondary pdp-wall__load-more-btn']")
time.sleep(2)
loadMoreButton.click()
time.sleep(2)
except:
print('Done Loading More')
# full_json = driver.page_source
temp_df = pd.DataFrame()
temp_df = scrape_bc(request, website)
full_df = pd.concat([full_df, temp_df], ignore_index = True)
time.sleep(7)
driver.quit()
break
return full_df
我希望 Pandas 数据框有 113 行和 3 列。 我得到一个有 18 行和 3 列的 pandas 数据帧。
【问题讨论】:
标签: python selenium selenium-webdriver beautifulsoup