使用BeautifulSoup进行网页抓取

时间:2017-05-14 09:09:22

标签: python beautifulsoup

我正在尝试从黄页中抓取数据,网站为this

我想要div class= search-results listing-group

我试过这个

parent = soup.find('div',{'class':"search-results listing-group"})

但是,我没有得到任何结果。

3 个答案:

答案 0 :(得分:0)

此URL具有防刮保护功能,可抵御程序化HTML提取。这就是为什么你没有得到任何输出的主要原因。您可以通过检查从请求返回的原始数据来看到这一点:

from bs4 import BeautifulSoup
import requests
url = "https://www.yellowpages.com.au/find/boat-yacht-sales/melbourne-vic"
soup = BeautifulSoup(requests.get(url).text)

print(soup)

摘录:

  

当在线数据保护服务检测到来自您的计算机网络的请求似乎违反了我们网站的使用条款时,会出现此页面。

答案 1 :(得分:0)

你在使用请求吗? 看来网页不允许自动抓取,至少使用Beautiful Soup。 我试着为你抓一下,这就是我在内容中看到的。

<p style="font-weight: bold;">Why did this happen?</p>
 <p style="margin-top: 20px;">This page appears when online data protection services detect requests coming from your computer network which appear to be in violation of our website's terms of use.</p>
 </div>, <div style="border-bottom: 1px #E7E7E7 solid;
                                 margin-top: 20px;
                                 margin-bottom: 20px;
                                 height: 1px;
                                 width: 100%;">
 </div>, <div style="margin-left: auto;
                                 margin-right: auto;
                                 font-size: 20px;
                                 max-width: 460px;
                                 text-align: center;">
                         We value the quality of content provided to our customers, and to maintain this, we would like to ensure real humans are accessing our information.</div>, <div style="margin-left: auto;
                                 margin-right: auto;
                                 margin-top: 30px;
                                 max-width: 305px;">

您可能必须尝试其他(合法)方法来抓取它。

答案 2 :(得分:0)

您正在访问的页面似乎不允许静态抓取,您需要使用像这样的硒预先抓取..

from bs4 import BeautifulSoup
import requests
from selenium import webdriver

url = "https://www.yellowpages.com.au/find/boat-yacht-sales/melbourne-vic"

driver=webdriver.Chrome(executable_path="{location}/chromedriver")
driver.get(url)
content_element = driver.find_elements_by_xpath("//div[@class='search-results 
listing-group']")
content_html = content_element[0].get_attribute("innerHTML")
soup = BeautifulSoup(content_html, "html.parser")
print soup

因为类名包含空格,所以你需要使用xpath或id之类的东西来获取数据。 有关提前抓取的更多信息,请阅读以下内容: https://medium.com/dualcores-studio/advanced-web-scraping-in-python-d19dfccba235