Python uses bs4 to obtain 58 city classifications in the same city

Source: Internet
Author: User
This article mainly introduces how Python uses bs4 to obtain 58 city classifications in the same city. It involves the skills of using the BeautifulSoup library to parse html pages in Python, for more information about how to use Python bs4 to obtain 58 city classifications, see the following example. Share it with you for your reference. The details are as follows:

# -*- coding:utf-8 -*-#! /usr/bin/pythonimport urllibimport os, datetime, sysfrom bs4 import BeautifulSoupreload(sys) sys.setdefaultencoding( "utf-8" ) __BASEURL__ = ""__INITURL__ = ""soup=BeautifulSoup(urllib.urlopen(__INITURL__))lv1Elements = soup.html.body.section.find('p', 'relative').find('dl', 'secitem')('a',href=True)f=open('data.txt', 'w')for element in lv1Elements[1:]:  f.write((element.get_text() + '\r\n'))  print element.get_text()  url = __BASEURL__ + element.get('href')  print url  soup=BeautifulSoup(urllib.urlopen(url))  lv2Elements = soup.html.body.section.find('p', 'relative').find('dl', 'secitem').find('p', 'subarea').find_all('a')  texts = [t.get_text() for t in lv2Elements]  f.write(' '.join(texts) + '\r\n\r\n')f.close()

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.