MCPcopy Create free account
hub / github.com/ZiniuLu/Python-100-Days / main

Function main

Day66-75/code/example03.py:8–23  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

6
7
8def main():
9 # 通过requests第三方库的get方法获取页面
10 resp = requests.get('http://sports.sohu.com/nba_a.shtml')
11 # 对响应的字节串(bytes)进行解码操作(搜狐的部分页面使用了GBK编码)
12 html = resp.content.decode('gbk')
13 # 创建BeautifulSoup对象来解析页面(相当于JavaScript的DOM)
14 bs = BeautifulSoup(html, 'lxml')
15 # 通过CSS选择器语法查找元素并通过循环进行处理
16 # for elem in bs.find_all(lambda x: 'test' in x.attrs):
17 for elem in bs.select('a[test]'):
18 # 通过attrs属性(字典)获取元素的属性值
19 link_url = elem.attrs['href']
20 resp = requests.get(link_url)
21 bs_sub = BeautifulSoup(resp.text, 'lxml')
22 # 使用正则表达式对获取的数据做进一步的处理
23 print(re.sub(r'[\r\n]', '', bs_sub.find('h1').text))
24
25
26if __name__ == '__main__':

Callers 1

example03.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected