【发布时间】:2018-06-23 10:03:26
【问题描述】:
我在抓取the webpage 时遇到问题
网址从 1 开始增加 30。它包含许多页面,其中包含肯尼亚的中学列表。每个页面都有 30 所学校的列表。我想用以下代码抓取所有数据,但它只给出一页的内容,即 30 所学校。我已经对 url 进行了字符串格式化,但仍然返回一页的数据。我的代码:
#IMPORTING RELEVANT PACKAGES FOR THE WORK
import requests
from bs4 import BeautifulSoup
import time
#DEFINING THE FIRST WEBPAGE
num = 1
#STRING FORMATTING THE URL TO CAPTURE DIFFRENT PAGES
url = 'https://www.kenyaplex.com/schools/?start={}&SchoolType=private-secondary-schools'.format(num)
#DEIFING THE BROWSER HEADERS SO THAT CAN WORK ON IT WITHOUT ERRORS
headers = {'User-Agent':'Mozilla'}
#GOING THROUGH ALL THE PAGES AND THE LINKS
while num < 452:
url = 'https://www.kenyaplex.com/schools/?start={}&SchoolType=private-secondary-schools'.format(num)
time.sleep(1)
num += 30
response = requests.get(url,headers)
soup = BeautifulSoup(response.text,'html.parser')
school_info = soup.find_all('div', attrs={'class':'c-detail'})
#EXTRACTING SPECIFIC RECORDS
records = []
for name in school_info:
Name_of_The_School = name.find('a').text
Location_of_The_School = name.contents[2][2:]
Contact_of_The_School = name.contents[4]
Information_Link = name.find('a')['href']
#converting the records to a tuple
records.append((Name_of_The_School,
Location_of_The_School,
Contact_of_The_School,
Information_Link))
#EXPORTING TO A PANDAS FILE
import pandas as pd
df = pd.DataFrame(records, columns = ['Name of The School',
'Location of The School',
'Contact of The School',
'Information_Link'])
df.to_csv('PRIVATE_SECONDARY.csv', index = False, encoding = 'utf-8')
【问题讨论】: