2016-08-18 1 views
1

나는 파이썬과 BeautifulSoup를 사용하여 eBay 추천 컬렉션에 들어가고 컬렉션 내의 모든 제품의 URL을 검색하는 웹 스크 레이 핑 도구를 만들려고합니다 (대부분의 컬렉션에는 17 개 제품이 있지만 일부는 약간 더 많거나 적음). http://www.ebay.com/cln/ebayhomeeditor/Surface-Study/324079803018제품 페이지 링크를위한 이베이의 추천 컬렉션 모집

여기 내 코드는 지금까지의 :

import requests 
from bs4 import BeautifulSoup 

url = 'http://www.ebay.com/cln/ebayhomeeditor/Surface-Study/324079803018' 
soup = BeautifulSoup(requests.get(url).text, 'html.parser') 

product_links = [] 

item_thumb = soup.find_all('div', attrs={'class':'itemThumb'}) 
for link in item_thumb: 
    product_links.append(link.find('a').get('href')) 

print product_links 

이 스크레이퍼 목록 product_links 17 개 링크를 추가해야합니다 여기에 내 코드에서 긁어 시도 컬렉션의 URL입니다. 그러나 일부분 만 작동합니다. 특히, 17 개의 링크가 모두 동일한 HTML 태그 및 속성 내에서 발견 되더라도 처음 12 개의 제품 링크 만 매번 긁어서 남은 5는 그대로 둡니다. 의 기능은 무엇

<script escape-xml="true"> 
     if (typeof(collectionState) != 'object') { 
      var collectionState = { 
       itemImageSize: {sWidth: 280, sHeight: 280, lWidth: 580, lHeight: 620}, 
       page: 1, 
       totalPages: 2, 
       totalItems: 17, 
       pageId: '2057253', 
       currentUser: '', 
       collectionId: '323101965012', 
       serviceHost: 'svcs.ebay.com/buying/collections/v1', 
       owner: 'ebaytecheditor', 
       csrfToken: '', 
       localeId: 'en-US', 
       siteId: 'EBAY-US', 
       countryId: 'US', 
       collectionCosEnabled: 'true', 
       collectionCosHostExternal: 'https://api.ebay.com/social/collection/v1', 
       collectionCosEditEnabled: 'true', 
       isCollectionReorderEnabled: 'false', 
       isOwnerSignedIn: false || false, 
       partiallySignedInUser: '@@[email protected]@[email protected]@', 
       baseDomain: 'ebay.com', 
       currentDomain: 'www.ebay.com', 
       isTablet: false, 
       isMobile: false, 
       showViewCount: true 
      }; 
     } 
    </script> 

: 페이지의 HTML 코드를 좀 더 자세히 보면, 내가 찾은 유일한 차이점은 처음 12 개 링크와 최종 5 내가 여기에 포함 된 한 XML 스크립트의 조각으로 분리되어 있다는 것입니다 이 스크립트? 이 스크립트가 내 스크레이퍼가 최종 5 개의 링크를 다 쳤던 이유는 아닌가? 이 문제를 해결하고 마지막 다섯 부분을 감출 수있는 방법이 있습니까?

마지막 몇 요청 http://www.ebay.com/cln/_ajax/2/ebayhomeeditor/324079803018아약스를 통해 생성되는
+0

JavaScript를 사용하여 다음 5 개의 링크가로드되기 때문에 이러한 현상이 발생합니다. –

답변

0

:

enter image description here

URL은 일부 제품 ID입니다 을해야합니다 ebayhomeeditor 무엇을 사용하여 구성되어 있습니다 둘 다 방문하는 페이지의 원래 URL에 있습니다.

데이터를 다시 가져 오는 데 필수적인 유일한 매개 변수는 itemsPerPage입니다. 나머지는 가지고 놀 수 있으며 어떤 효과가 있는지 확인할 수 있습니다.

params = {"itemsPerPage": "10"} 
soup= BeautifulSoup(requests.get("http://www.ebay.com/cln/_ajax/2/ebayhomeeditor/324079803018", params=params).content) 
print([a["href"] for a in soup.select("div.itemThumb div.itemImg.image.lazy-image a[href]")]) 

당신을 줄 것이다 :

['http://www.ebay.com/itm/yamazaki-home-tower-book-end-white-stationary-holder-desktop-organizing-steel/171836462366?hash=item280240551e', 'http://www.ebay.com/itm/tetris-constructible-interlocking-desk-lamp-neon-light-nightlight-by-paladone/221571335719?hash=item3396ae4627', 'http://www.ebay.com/itm/iphone-docking-station-dock-native-union-new-in-box/222202878086?hash=item33bc52d886', 'http://www.ebay.com/itm/turnkey-pencil-sharpener-silver-office-home-school-desk-gift-peleg-design/201461359979?hash=item2ee808656b', 'http://www.ebay.com/itm/himori-weekly-times-desk-notepad-desktop-weekly-scheduler-30-weeks-planner/271985620013?hash=item3f539b342d'] 

을 그래서 모든 URL 얻기 위해 함께 퍼팅 :

In [23]: params = {"itemsPerPage": "10"} 

In [24]: with requests.Session() as s: 
    ....:   soup1 = BeautifulSoup(s.get('http://www.ebay.com/cln/ebayhomeeditor/Surface-Study/324079803018').content, 
    ....:        "html.parser") 
    ....:   main_urls = [a["href"] for a in soup1.select("div.itemThumb div.itemImg.image.lazy-image a[href]")] 
    ....:   soup2 = BeautifulSoup(s.get("http://www.ebay.com/cln/_ajax/2/ebayhomeeditor/324079803018", params=params).content, 
    ....:        "html.parser") 
    ....:   print(len(main_urls)) 
    ....:   main_urls.extend(a["href"] for a in soup2.select("div.itemThumb div.itemImg.image.lazy-image a[href]")) 
    ....:   print(main_urls) 
    ....:   print(len(main_urls)) 
    ....:  
12 
['http://www.ebay.com/itm/archi-desk-accessories-pen-cup-designed-by-hsunli-huang-for-moma/262435041373?hash=item3d1a58f05d', 'http://www.ebay.com/itm/moorea-seal-violet-light-crane-scissors/201600302323?hash=item2ef0507cf3', 'http://www.ebay.com/itm/kikkerland-photo-holder-with-6-magnetic-wooden-clothespin-mh69-cable-47-long/361394782932?hash=item5424cec2d4', 'http://www.ebay.com/itm/authentic-22-design-studio-merge-concrete-pen-holder-desk-office-pencil/331846509549?hash=item4d4397e3ed', 'http://www.ebay.com/itm/supergal-bookend-by-artori-design-ad103-metal-black/272273290322?hash=item3f64c0b452', 'http://www.ebay.com/itm/elago-p2-stand-for-ipad-tablet-pcchampagne-gold/191527567203?hash=item2c97eebf63', 'http://www.ebay.com/itm/this-is-ground-mouse-pad-pro-ruler-100-authentic-natural-retail-100/201628986934?hash=item2ef2062e36', 'http://www.ebay.com/itm/hot-fuut-foot-rest-hammock-under-desk-office-footrest-mini-stand-hanging-swing/152166878943?hash=item236dda4edf', 'http://www.ebay.com/itm/unido-silver-white-black-led-desk-office-lamp-adjustable-neck-brightness-level/351654910666?hash=item51e0441aca', 'http://www.ebay.com/itm/in-house-black-desk-office-organizer-paper-clips-memo-notes-monkey-business/201645856763?hash=item2ef30797fb', 'http://www.ebay.com/itm/rifle-paper-co-2017-maps-desk-calendar-illustrated-worldwide-cities/262547131670?hash=item3d21074d16', 'http://www.ebay.com/itm/muji-erasable-pen-black/262272348079?hash=item3d10a66faf', 'http://www.ebay.com/itm/rifle-paper-co-2017-maps-desk-calendar-illustrated-worldwide-cities/262547131670?hash=item3d21074d16', 'http://www.ebay.com/itm/muji-erasable-pen-black/262272348079?hash=item3d10a66faf', 'http://www.ebay.com/itm/yamazaki-home-tower-book-end-white-stationary-holder-desktop-organizing-steel/171836462366?hash=item280240551e', 'http://www.ebay.com/itm/tetris-constructible-interlocking-desk-lamp-neon-light-nightlight-by-paladone/221571335719?hash=item3396ae4627', 'http://www.ebay.com/itm/iphone-docking-station-dock-native-union-new-in-box/222202878086?hash=item33bc52d886', 'http://www.ebay.com/itm/turnkey-pencil-sharpener-silver-office-home-school-desk-gift-peleg-design/201461359979?hash=item2ee808656b', 'http://www.ebay.com/itm/himori-weekly-times-desk-notepad-desktop-weekly-scheduler-30-weeks-planner/271985620013?hash=item3f539b342d'] 
19 

In [25]: 

그래서 그냥에 세트를 사용하여 반환됩니다 것과 약간의 중복이를 list에 main_urls 또는 호출 집합을 저장하십시오.

왜 그런 일이 발생했는지 정확히 알지 못했지만, 아쉽게도 ajax 호출에서 "totalItems : 17"을 파싱하여 첫 번째 호출 후 main_urls의 길이를 뺀 다음 {"itemsPerPage": str(len(main_urls) - int(parsedtotal))} 나는 그것에 대해 너무 걱정하지 않을 것이다.

+0

이 작업을 수행 할 EBay API가 있습니까? – pratibha