2016-12-06 4 views
0

私は現在、シンガポールのトップ500のレストランを掻き回そうとしています。しかし、私の現在のコードは最初の30個だけを引っ張って、最初の30個が500個のレコードに達するまでループし続けます。最初の30枚を印刷し、次の30枚を次のページに印刷したいと思います。私は誰かが私のコードを見て、なぜこれをやっているのかを知ることができるのだろうかと思っていました。ループしていない複数のWebページを掻き回すループ

#loop to move into the next pages. entries are in increments of 30 per page 
for i in range(0, 500, 30): 
    #url format offsets the restaurants in increments of 30 after the oa 
    #change key and geography here 
    url1 = 'https://www.tripadvisor.com/Restaurants-g294265-oa' + str(i) + 'Singapore.html#EATERY_LIST_CONTENTS' 
    r1 = requests.get(url1) 
    data1 = r1.text 
    soup1 = BeautifulSoup(data1, "html.parser") 
    for link in soup1.findAll('a', {'property_title'}): 
     #change key here 
     restaurant_url = 'https://www.tripadvisor.com/Restaurant_Review-g294265-' + link.get('href') 
     print restaurant_url 

答えて

2

私はあなたがここで間違ったURLを作っていると思う:

url1 = 'https://www.tripadvisor.com/Restaurants-g294265-oa' + str(i) + 'Singapore.html#EATERY_LIST_CONTENTS' 

を正しいURLの形式は次のようになります。

url1 = 'https://www.tripadvisor.com/Restaurants-g294265-oa{0}-Singapore.html#EATERY_LIST_CONTENTS'.format(i) 

"ページオフセット" の後にダッシュを注意してください。


私もウェブこするセッションを維持し、変数の命名改善するだろう。また

import requests 
from bs4 import BeautifulSoup 


with requests.Session() as session: 
    for offset in range(0, 500, 30): 
     url = 'https://www.tripadvisor.com/Restaurants-g294265-oa{0}-Singapore.html#EATERY_LIST_CONTENTS'.format(offset) 

     soup = BeautifulSoup(session.get(url).content, "html.parser") 
     for link in soup.select('a.property_title'): 
      restaurant_url = 'https://www.tripadvisor.com/Restaurant_Review-g294265-' + link.get('href') 
      print(restaurant_url) 

を、およそ追加遅延が後続の要求の間web-scraping citizen方が良いと思います。

+0

チャームのように働いた。そして、そのセッションポストをリンクしてくれてありがとう。私はこのコミュニティには新しいので何かが役に立ちます! – dtrinh

関連する問題