2016-12-26 78 views
1

我在過去的10個小時裏一直在處理這個問題,而且我仍然無法解決它。該代碼適用於某些人,但它不適合我。soup.findAll()爲div類屬性返回null Beautifulsoup

主要目的是提取谷歌結果的網址爲https://www.google.com.au/webhp?num=100&gl=au&hl=en#q=site:focusonfurniture.com.au&gl=au&hl=en&start=0

而這裏所有的網頁是我的代碼:

# -*- coding: utf-8 
from bs4 import BeautifulSoup 
import urllib, urllib2 

def google_scrape(query): 
    address = "https://www.google.com.au/webhp?num=100&gl=au&hl=en#q=site:focusonfurniture.com.au&gl=au&hl=en&start=0".format (urllib.quote_plus(query)) 
    request = urllib2.Request(address, None, {'User-Agent':'Mozilla/43.0.1'}) 
    urlfile = urllib2.urlopen(request) 
    html = urlfile.read() 
    soup = BeautifulSoup(html) 
    linkdictionary = {} 

    for li in soup.findAll('div', attrs={'class' : 'g'}): # It never goes inside this for loop as find.All results Null 

     sLink = li.find('.r a') 
     print sLink['href'] 

    return linkdictionary 

if __name__ == '__main__': 
    links = google_scrape('beautifulsoup') 
    print links 

我得到{}爲result.The代碼soup.findAll('div', attrs={'class' : 'g'})被返回null和因此,我無法取得任何結果。

我正在使用BS4和Python 2.7。請幫我瞭解爲什麼代碼無法正常工作。任何幫助將非常感激。

此外,如果有人能夠深入瞭解爲什麼相同的代碼適用於某些人而不適用於其他人呢? (上次發生在我身上)。 謝謝。

+1

那麼,一個問題,我看到直線距離是,你試圖把查詢到你的'address'字符串使用'.format()',但在你的字符串中沒有佔位符來告訴Python在哪裏放置查詢。 – kindall

+0

@kindall即使刪除它也不起作用。你有沒有在你的電腦上運行相同的代碼?它工作嗎? –

+1

更好,如果你使用內部API(或使用硒) 這個http://stackoverflow.com/questions/4082966/what-are-the-alternatives-now-the-the-google-web-search- API已被棄用/ 11206266#11206266和此https://github.com/scraperwiki/google-search-python可以幫助! – wu4m4n

回答

0

這是你可以做的一個例子。 你需要硒和phantomjs(此模擬瀏覽器)

import selenium.webdriver 
from pprint import pprint 
import re 

url = 'https://www.google.com.au/webhp?num=100&gl=au&hl=en#q=site:focusonfurniture.com.au&gl=au&hl=en&start=0' 
driver = selenium.webdriver.PhantomJS() 
driver.get(url) 
html = driver.page_source 


regex = r"<cite>(https:\/\/www\.focusonfurniture\.com\.au\/[\/A-Z]+)<\/cite>" 

result = re.findall(re.compile(regex, re.IGNORECASE | re.MULTILINE),html) 
for url in result: 
    print url 

driver.quit() 

結果:

https://www.focusonfurniture.com.au/delivery/ 
https://www.focusonfurniture.com.au/terms/ 
https://www.focusonfurniture.com.au/disclaimer/ 
https://www.focusonfurniture.com.au/dining/ 
https://www.focusonfurniture.com.au/bedroom/ 
https://www.focusonfurniture.com.au/catalogue/ 
https://www.focusonfurniture.com.au/mattresses/ 
https://www.focusonfurniture.com.au/clearance/ 
https://www.focusonfurniture.com.au/careers/ 
+0

謝謝你的回覆。我正在處理一些關於讓Selenium正確的錯誤。但我希望它能奏效。讓我們來看看。 –