2016-12-26 107 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正确的错误。但我希望它能奏效。让我们来看看。 –