My first blog, hahaha, record my python's way to the next step!
Today, I wrote a simple reptile.
Using Python's requests and beautifulsoup modules, Python 2.7.12 can use PIP for module installation directly on the command line. The core of the crawler is to use BeautifulSoup's SELECT statement to obtain the required information.
install requestspip install bs4
Take Wuhan 2017 5 ~ July history as an example crawl historical weather data of Wuhan in the weather net.
July the corresponding URL is http://lishi.tianqi.com/wuhan/201707.html
1.requests Module for Web content
url=‘http://lishi.tianqi.com/wuhan/201707.html‘response = requests.get(url) soup = BeautifulSoup(response.text, ‘html.parser‘)
2. Use the. Select statement to find the DIV where the weather data is located in the Web page
weather_list = soup.select(‘div[class="tqtongji2"]‘)
3. Find the date, the highest temperature, the lowest temperature, the weather and other data, and use li.string to obtain information from Li.
ul_list = weather.select(‘ul‘)for ul in ul_list: li_list= ul.select(‘li‘) for li in li_list: li.string.encode(‘utf-8‘) #具体的天气信息
The specific code is implemented as follows:
#encoding: Utf-8 Import RequestsFrom BS4 import beautifulsoup urls = ["Http://lishi.tianqi.com/wuhan/201707.html","Http://lishi.tianqi.com/wuhan/201706.html","Http://lishi.tianqi.com/wuhan/201705.html"]File =Open' Wuhan_weather.csv ',' W ')For URLIn Urls:response = requests.Get (URL) soup = beautifulsoup (response.Text' Html.parser ') weather_list = Soup.select (' div[class= ' Tqtongji2 "])For weatherIn weather_list:weather_date = Weather.select ( ' a ') [0]. string.encode ( ' utf-8 ') ul_list = Weather.select ( ' ul ') I=0 for ul in ul_list:li_list= Ul.select ( ' li ') str=for li in li_list:str + = Li. String.encode ( ' utf-8 ') + ', ' if i!= 0: file. Write (Str+ \ n ') i+=1 file.close ()
The final result:
Crawling data using the SELECT statement is as simple as a regular expression.
Regular expression is not very understanding, and so clear, and then to write a summary.
Move over from CSDN and experience the http://blog.csdn.net/haha_point/article/details/77197230
Python Crawl Weather Network historical weather data