问题
右键点击审查,然后在弹出的html源码中右键选择Copy–>Copy selector
得到
#topic > dl:nth-child(3) > div > div.newsbottom > ul > li:nth-child(8) > a
描述了我们想要获取的内容在html中的由外层到内层的位置/路径信息。
from bs4 import BeautifulSoup
import url_get
import urllib.request
def get_html(url):
page = urllib.request.urlopen(url) # 打开网页
htmlcode = page.read().decode("gbk") # 读取页面源码 ‘gbk’解决中文乱码问题,不用utf-8因为utf-8报错,可能是因为特殊字符不支持
return htmlcode
url = 'http://www.zjgsu.edu.cn/news/' #浙江工商大学新闻网
html = url_get.get_html(url) #获取html
soup = BeautifulSoup(html,'html.parser') #定义一个Soup对象
#topic > dl:nth-child(3) > div > div.newsbottom > ul > li:nth-child(8) > a
#Copy selector得到的
newses = soup.select('topic > dl:nth-of-type(3) > div > div.newsbottom > ul > li:nth-of-type(8) > a')
for news in newses:
print(new