2016-12-26 9 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

ためのすべてのページのGoogleの検索結果のURLを抽出することであり、ここに私のコードです:

# -*- 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を使用する(またはセレンを使用する)方が良いです this http://stackoverflow.com/questions/4082966/what-are-the-alternatives-now-that-the-google-web-search- api-has-been-deprecated/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

あなたの回答はたくさんあります。私はセレンの権利を得ることについていくつかの誤りに取り組んでいます。しかし、私はそれがうまくいくことを期待しています。どれどれ。 –

関連する問題