python-3.x - soup.find_all 返回空列表
问题描述
我对python很陌生,我正在尝试搜索指定的邮政编码并打印相应的城市,但是我一直无法这样做。
from bs4 import BeautifulSoup
import requests
import html.parser
# I am using Chrome as default browser
url = ("http://google.co.uk/search?=sk71nd")
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
'''我认为下面的课程会返回以下城市:城市:大曼彻斯特、布拉姆霍尔、斯托克波特大都会区,但我只得到一个空列表'''
print(soup.find_all("div", {'class': "zloOqf PZPZlf kno-fb-ctx"}))
是否可以搜索提供的邮政编码并打印结果城市?非常感谢
解决方案
尝试这个,
from bs4 import BeautifulSoup
import requests
import html.parser
import re
# I am using Chrome as default browser
data = []
data2 = []
url = ("https://en.wikipedia.org/wiki/List_of_postcode_districts_in_the_United_Kingdom")
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
#print(soup.prettify())
table = soup.find("table", {"class": "toc"})
for row in table.findAll("tr"):
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele])
print(data[1])
table = soup.find("table", {"class": "wikitable sortable"})
for row in table.findAll("tr"):
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data2.append([ele for ele in cols if ele])
print(data2)
data1 - 存储邮政编码 data2 - [邮政编码区、邮政编码区、邮政镇、原邮政县]
推荐阅读
- c++ - 如何帮助编译器优化 lambda 调用?
- docker - Docker 无法识别 64 位内核
- android - 流媒体开始时,Twitch 视频未自动播放
- javascript - 使用 ng build 构建应用程序时删除模块
- c - 如何在 Windows 内核模式下挂钩内存 I/O?
- java - 用分钟收集可用时间并删除繁忙时间的想法
- sql - 计算同一列中日期之间的差异但数字不同?
- c++ - (linux的)chrono::duration是否还包括线程暂停的时间?
- python - 在 Raspberry Pi 上运行 YOLOv5 时成功安装 coco 数据集后出现 Segmentation Fault Error(core dumped)
- android - Android 中的 Youtube 插入 API