2017-11-11 174 views
0

我在网站上做过网页抓取。它只在页面中取得前20个元素。如果我们向下滚动,其余元素将被加载。如何刮这些元素呢?有没有什么不同的方法来做到这一点?BeautifulSoup仅识别页面中的几个元素

import requests 
from bs4 import BeautifulSoup 

r=requests.get("https://www.century21.com/real-estate/rock-spring-ga/LCGAROCKSPRING/") 
c=r.content 
c 

soup=BeautifulSoup(c,"html5lib") 
soup 

all=soup.find_all("div",{"class":"property-card-primary-info"}) 
len(all) 

它只给出20个。不是全部。如何刮掉隐藏的元素呢?

+0

元素似乎滚动动作之后被加载,则可能需要另一种工具来提取它们。 – PRMoureu

+0

什么样的工具? –

+0

selenium可以工作,https://stackoverflow.com/questions/14583560/selenium-retrieve-data-that-loads-while-scrolling-down – PRMoureu

回答

1

使用硒向下滚动,然后你可以刮的内容其他

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

browser = webdriver.Chrome(executable_path=os.path.join(os.getcwd(),'chromedriver')) 
browser.get(link) 

body = browser.find_element_by_tag_name("body") 

no_of_pagedowns = 2 #Enter number of pages that you would like to scroll here 

while no_of_pagedowns: 
    body.send_keys(Keys.PAGE_DOWN) 
    no_of_pagedowns-=1 
1

有两种不同的方法。

第一个: 通过检索站点后面的数据API来使用网络抓取。您需要了解滚动后为网站带来的新信息。 要了解这一点,请在网络区域中打开浏览器开发工具(Chrome中的F12),并观察滚动后正在调用的内容。

第二个: 使用Selenium打开浏览器实例并像普通浏览器一样加载页面,滚动页面并检索信息。