2017-12-04 8 views
0
from bs4 import BeautifulSoup 
import urllib, time 
class scrap(object): 
    def __init__(self): 
     self.urls = ['https://www.onthemarket.com/for-sale/property/wigan/', 'https://www.onthemarket.com/for-sale/property/wigan/?page=1', 'https://www.onthemarket.com/for-sale/property/wigan/?page=2', 'https://www.onthemarket.com/for-sale/property/wigan/?page=3', 'https://www.onthemarket.com/for-sale/property/wigan/?page=4', 'https://www.onthemarket.com/for-sale/property/wigan/?page=6'] 
     self.telephones = [] 
    def extract_info(self): 
     for link in self.urls: 
      data = urllib.request.urlopen(link).read() 
      soup = BeautifulSoup(data, "lxml") 
      for tel in soup.findAll("span", {"class":"call"}): 
       self.telephones.append(tel.text.strip()) 
      time.sleep(1) 
     return self.telephones 

to = scrap() 
print(to.extract_info()) 

무엇이 잘못 되었나요? 이 코드는 두 번째 웹 사이트 뒤에 매달려 있습니다. 목록의 각 웹 페이지에서 전화 번호를 추출해야합니다. self.urls파이썬으로 여러 웹 페이지 긁기

+1

오류가 발생하면 – csharpcoder

+0

코드를 사용해 보았습니다. 모든 것이 잘 작동합니다. [9.3에서 끝났습니다] – ventik

+0

오류가 없습니다. 파이썬 셸 작업을하고 있지만 아무것도 반환하지 않습니다. 나는 Spyder를 Python 3.6과 함께 사용한다. 나는 5 분 이상 기다리고 아무 것도 일어나지 않는다. – FootAdministration

답변

1

검색어 매개 변수에 headers을 입력하고 이동하면됩니다. 이것을 시도하십시오 :

from bs4 import BeautifulSoup 
import requests, time 

class scrape(object): 

    def __init__(self): 
     self.urls = ['https://www.onthemarket.com/for-sale/property/wigan/', 'https://www.onthemarket.com/for-sale/property/wigan/?page=1', 'https://www.onthemarket.com/for-sale/property/wigan/?page=2', 'https://www.onthemarket.com/for-sale/property/wigan/?page=3', 'https://www.onthemarket.com/for-sale/property/wigan/?page=4', 'https://www.onthemarket.com/for-sale/property/wigan/?page=6'] 
     self.telephones = [] 

    def extract_info(self): 
     for link in self.urls: 
      data = requests.get(link,headers={"User-Agent":"Mozilla/5.0"}) #it should do the trick 
      soup = BeautifulSoup(data.text, "lxml") 
      for tel in soup.find_all("span",{"class":"call"}): 
       self.telephones.append(tel.text.strip()) 
      time.sleep(1) 
     return self.telephones 

crawl = scrape() 
print(crawl.extract_info()) 
+0

Btw, 귀하의 경우에는 두 개의 사이트가 작동하고 나머지는 그렇지 않은 것으로 나타났습니다. 그렇지만 제 경우에는 빈 목록이 있습니다. 그러나 요청 매개 변수에 헤더를 넣은 후 완벽하게 @FootAdministration을 처리했습니다. – SIM

+0

감사합니다 Shahin 그것은 나를 위해 일했습니다! 좋은 대답! 좋은 하루 되세요! – FootAdministration