Google トレンド データをダウンロードし、PhantomJS を使用してページを読み込み、必要なデータを抽出しようとしています。URL に 1 つのキーワードのみを使用してコードを実行すると (URL の例: https://www.google.com/trends/explore?date=today%203-m&geo=US&q=Blue )、正常に動作します。2 番目のキーワードを追加するとすぐに (URL の例: https://www.google.com/trends/explore?date=today%203-m&geo=US&q=Blue,Red) PhantomJS がページを正しくロードしなくなり、必要なデータを見つけることができません。ブラウザの待機時間を増やしてみたり、さまざまなキーワードを試してみましたが、成功しませんでした。私はアイデアがなく、URLをわずかに変更した後にプログラムが機能しなくなった理由を単純に理解していません(タグとページ構造は両方のURLでほぼ同じであるため、問題はタグが同じ名前を持たなくなったことではありません前)問題のコードは次のとおりです。
# Reading google trends data
google_trend_array = []
url = 'https://www.google.com/trends/explore?date=today%203-m&geo=US&q=Blue,Red'
browser = webdriver.PhantomJS('...\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe')
ran_smooth = False
time_to_sleep = 3
# ran_smooth makes sure that page has loaded and necessary code was extracted, if not it will try to load the page again
while ran_smooth is False:
browser.get(url)
time.sleep(time_to_sleep)
soup = BeautifulSoup(browser.page_source, "html.parser") # BS object to use bs4
table = soup.find('div', {'aria-label': 'A tabular representation of the data in the chart.'})
# If page didn't load, this try will throw an exception
try:
# Copies all the data out of google trends table
for col in table.findAll('td'):
# google has both dates and trend values, the following function ensures that we only read the trend values
if col.string.isdigit() is True:
trend_number = int(col.string)
google_trend_array.append(trend_number)
# program ran through, leave while loop
ran_smooth = True
except AttributeError:
print 'page not loading for term ' + str(term_to_trend) + ', trying again...'
time_to_sleep += 1 # increase time to sleep so that page can load
print google_trend_array