News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

Python crawls website data (including code and explanation)

posted on 2023-05-21 16:29     read(674)     comment(0)     like(9)     collect(3)


Tip: This crawling is carried out using xpath , and it is OK to follow the order of the articles;

Article directory

foreword

1. Preparation for data collection

1. Observe the url rule

2. Set the crawling location and path (xpath)

2. Data collection

1. Create a dataframe to store data

2. Start crawling

3. Export the data into a csv table

Summarize


foreword

The website crawled this time is the Fangtianxia website;

It contains a lot of real estate information: https://newhouse.fang.com/house/s/b81-b91/

I did a step-by-step screening on the website, that is, to select the listings in Beijing and its surrounding areas. If you want to crawl the listing information in other cities, it is also very simple, just change the url information.

1. Preparation for data collection

1. Observe the url rule

It is observed that there are many webpages for housing listings in Beijing and surrounding areas, and the pattern of URLs can be found by turning a few pages:

The URL is: https://newhouse.fang.com/house/s/ + b81-b9 X   + /; where X is the page number

 Use for loop to traverse all pages:

  1. for i in range(33): # 每页20个小区,共648个小区
  2. url = 'https://newhouse.fang.com/house/s/b81-b9' + str(i+1) + '/'

pip install fake_useragent library:

fake-useragent can pretend to generate the User Agent value in the headers request header, and disguise the crawler as the normal operation of the browser.

!pip install fake_useragent

Import the packages that will be used next: 

  1. ## 导包
  2. from lxml import etree
  3. import requests
  4. from fake_useragent import UserAgent
  5. import pandas as pd
  6. import random
  7. import time
  8. import csv

Set request parameters: You need to replace the two values ​​of 'cookie' and 'referer':

'cookie': Every time you visit the website server, the server will set a cookie locally to indicate the identity of the visitor. Remember to manually fill in a cookie according to the fixed method every time you use it.

 'referer': request parameter, identifying which page the request came from.

  1. # 设置请求头参数:User-Agent, cookie, referer
  2. headers = {
  3. 'User-Agent' : UserAgent().random,
  4. 'cookie' : "global_cookie=kxyzkfz09n3hnn14le9z39b9g3ol3wgikwn; city=www; city.sig=OGYSb1kOr8YVFH0wBEXukpoi1DeOqwvdseB7aTrJ-zE; __utmz=147393320.1664372701.10.4.utmcsr=mp.csdn.net|utmccn=(referral)|utmcmd=referral|utmcct=/mp_blog/creation/editor; csrfToken=KUlWFFT_pcJiH1yo3qPmzIc_; g_sourcepage=xf_lp^lb_pc'; __utmc=147393320; unique_cookie=U_bystp5cfehunxkbjybklkryt62fl8mfox4z*3; __utma=147393320.97036532.1606372168.1664431058.1664433514.14; __utmt_t0=1; __utmt_t1=1; __utmt_t2=1; __utmt_t3=1; __utmt_t4=1; __utmb=147393320.5.10.1664433514",
  5. # 设置从何处跳转过来
  6. 'referer': 'https://newhouse.fang.com/house/s/b81-b91/'
  7. }

Please refer to the link for the specific modification method:

[Tencent document] How to change 'cookie' and 'referer':
https://docs.qq.com/doc/DR2RzUkJTQXJ5ZGt6

I can only follow the link, and I have been reviewing but 555~ 

2. Set the crawling location and path (xpath)

Because crawling data mainly relies on 'determining the location of the target data', you must first figure out the location of the target data (which part of the div is located);

First send the request: 

  1. url = 'https://newhouse.fang.com/house/s/b81-b91/'# 首页网址URL
  2. page_text = requests.get(url=url, headers=headers).text# 请求发送
  3. tree = etree.HTML(page_text)#数据解析

The data I want to crawl is mainly: real estate name, number of comments, house area, detailed address, area, and average price .

The code has been pasted below, and the specific method description is still a link: 

[Tencent Documents] Explanation on obtaining specific crawling locations
https://docs.qq.com/doc/DR3BFRW1lVGFRU0Na

  1. # 小区名称
  2. name = [i.strip() for i in tree.xpath("//div[@class='nlcd_name']/a/text()")]
  3. print(name)
  4. print(len(name))
  5. # 评论数
  6. commentCounts = tree.xpath("//span[@class='value_num']/text()")
  7. print(commentCounts)
  8. print(len(commentCounts))
  9. # 房屋面积
  10. buildingarea = [i.strip() for i in tree.xpath("//div[@class='house_type clearfix']/text()")]
  11. print(buildingarea)
  12. print(len(buildingarea))
  13. # 详细地址
  14. detailAddress = tree.xpath("//div[@class='address']/a/@title")
  15. print(detailAddress)
  16. print(len(detailAddress))
  17. # 所在区
  18. district = [i.strip() for i in tree.xpath("//div[@class='address']//span[@class='sngrey']/text()")]
  19. print(district)
  20. print(len(district))
  21. # 均价
  22. num = tree.xpath("//div[@class='nlc_details']/div[@class='nhouse_price']/span/text() | //div[@class='nlc_details']/div[@class='nhouse_price']/i/text()")
  23. unit = tree.xpath("//div[@class='nlc_details']/div[@class='nhouse_price']/em/text()")
  24. price = [i+j for i,j in zip(num, unit)]
  25. print(price)
  26. print(len(price))

The data collected at this time also contains symbols or units such as [] square brackets, — horizontal bar, "square meter", so simple split processing should be performed on the data to extract the really needed data:

  1. # 评论数处理
  2. commentCounts = [int(i.split('(')[1].split('条')[0]) for i in commentCounts]
  3. print(commentCounts)
  4. # 详细地址处理
  5. detailAddress = [i.split(']')[1] for i in detailAddress]
  6. print(detailAddress)
  7. # 所在区字段处理
  8. district = [i.split('[')[1].split(']')[0] for i in district]
  9. print(district)
  10. # 房屋面积处理
  11. t = []
  12. for i in buildingarea:
  13. if i != '/' and i != '':
  14. t.append(i.split('—')[1].split('平米')[0])
  15. print(t)
  16. print(len(t))

2. Data collection

1. Create a dataframe to store data

  1. df = pd.DataFrame(columns = ['小区名称', '详细地址', '所在区', '均价', '评论数'])
  2. df

2. Start crawling

For the convenience of this map, only the first 10 pages are crawled, because the listings in the back often have little information, either without area information or without the area where they are located. 

  1. for k in range(10):
  2. url = 'https://newhouse.fang.com/house/s/b81-b9' + str(k+1) + '/'
  3. page_text = requests.get(url=url, headers=headers).text #请求发送
  4. tree = etree.HTML(page_text) #数据解析
  5. # 小区名称
  6. name = [i.strip() for i in tree.xpath("//div[@class='nlcd_name']/a/text()")]
  7. # 评论数
  8. commentCounts = tree.xpath("//span[@class='value_num']/text()")
  9. # 详细地址
  10. detailAddress = tree.xpath("//div[@class='address']/a/@title")
  11. # 所在区
  12. district = [i.strip() for i in tree.xpath("//div[@class='address']//text()")]
  13. # 均价
  14. num = tree.xpath("//div[@class='nlc_details']/div[@class='nhouse_price']/span/text() | //div[@class='nlc_details']/div[@class='nhouse_price']/i/text()")
  15. unit = tree.xpath("//div[@class='nlc_details']/div[@class='nhouse_price']/em/text()")
  16. price = [i+j for i,j in zip(num, unit)]
  17. #评论数处理
  18. commentCounts = [int(i.split('(')[1].split('条')[0]) for i in commentCounts]
  19. #详细地址处理
  20. tmp1 = []
  21. for i in detailAddress:
  22. if ']' in i:
  23. tmp1.append(i.split(']')[1])
  24. continue
  25. tmp1.append(i)
  26. detailAddress = tmp1
  27. #所在区处理
  28. tmp2 = []
  29. for i in district:
  30. if ']' in i and '[' in i:
  31. tmp2.append(i.split(']')[0].split('[')[1])
  32. district = tmp2
  33. dic = {'小区名称':name, '详细地址':detailAddress, '所在区':district, '均价':price, '评论数':commentCounts}
  34. df2 = pd.DataFrame(dic)
  35. df = pd.concat([df,df2], axis=0)
  36. print('第{}页爬取成功, 共{}条数据'.format(k+1, len(df2)))
  37. print('全部数据爬取成功')

3. Export the data into a csv table

df.to_csv('北京小区数据信息.csv',index=None)

Summarize

To be honest, the crawling method used in this article is simple and the information is correct, but there are some deficiencies. For example, when some real estate information is vacant, it cannot be collected according to null, but an error will be reported, so my existing solution is in Manually set conditions in the loop to skip vacant information.

I will continue to optimize this method~



Category of website: technical article > Blog

Author:Disheartened

link:http://www.pythonblackhole.com/blog/article/25282/e821404585b4c30c0945/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

9 0
collect article
collected

Comment content: (supports up to 255 characters)