gpt4 book ai didi

python - BeautifulSoup 用 python 抓取表 id

转载 作者:行者123 更新时间:2023-12-01 02:19:56 28 4
gpt4 key购买 nike

我是抓取新手,正在学习使用 BeautifulSoup,但我在抓取表格时遇到困难。对于我正在尝试解析的 HTML:

<table id="ctl00_mainContent_DataList1" cellspacing="0" > style="width:80%;border-collapse:collapse;"> == $0
<tbody>
<tr><td><table width="90%" cellpadding="5" cellspacing="0">...</table></td></tr>
<tr><td><table width="90%" cellpadding="5" cellspacing="0">...</table></td></tr>
<tr><td><table width="90%" cellpadding="5" cellspacing="0">...</table></td></tr>
<tr><td><table width="90%" cellpadding="5" cellspacing="0">...</table></td></tr>
...

我的代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup

quote_page = 'https://www.bcdental.org/yourdentalhealth/findadentist.aspx'
page = urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')

table = soup.find('table', id="ctl00_mainContent_DataList1")
rows = table.findAll('tr')

我收到AttributeError:“NoneType”对象没有属性“findAll”。我正在使用 python 3.6 和 jupyter 笔记本,以防万一。

编辑:我尝试解析的表格数据仅在请求搜索后显示在页面上(在 city 字段中,选择 Burnaby,然后点击搜索)。表 ctl00_mainContent_DataList1 是提交搜索后显示的牙医列表。

最佳答案

首先:我使用requests因为使用 cookie、 header 等更容易。

<小时/>

页面由 ASP.net 生成它发送值 __VIEWSTATE , __VIEWSTATEGENERATOR , __EVENTVALIDATION您必须发送POST也请求。

您必须使用 GET 加载页面然后你就可以获得这些值。
您还可以使用request.Session()获取也可能需要的cookie。

接下来,您必须从表单复制值并添加参数,然后使用 POST 发送它。 。

在代码中我只放置了总是发送的参数。

'526'代码为Vancouver 。其他代码您可以在 <select> 中找到标签。
如果您想要其他选项,那么您可能需要添加其他参数。

即。 ctl00$mainContent$chkUndr4Ref: on用于Children: 3 & Under - Diagnose & Refer

编辑:因为里面 <tr><table>所以find_all('tr')返回太多元素(外部 tr 和内部 tr )和 and later find_all('td') give the same TD many times. I changed find_all('tr') into find_all('table')` 它应该停止重复数据。

import requests
from bs4 import BeautifulSoup

url = 'https://www.bcdental.org/yourdentalhealth/findadentist.aspx'

# --- session ---

s = requests.Session() # to automatically copy cookies
#s.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0'})

# --- GET request ---

# get page to get cookies and params
response = s.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# --- set params ---

params = {
# session - copy from GET request
#'EktronClientManager': '',
#'__VIEWSTATE': '',
#'__VIEWSTATEGENERATOR': '',
#'__EVENTVALIDATION': '',
# main options
'ctl00$terms': '',
'ctl00$mainContent$drpCity': '526',
'ctl00$mainContent$txtPostalCode': '',
'ctl00$mainContent$drpSpecialty': 'GP',
'ctl00$mainContent$drpLanguage': '0',
'ctl00$mainContent$drpSedation': '0',
'ctl00$mainContent$btnSearch': '+Search+',
# other options
#'ctl00$mainContent$chkUndr4Ref': 'on',
}

# copy from GET request
for key in ['EktronClientManager', '__VIEWSTATE', '__VIEWSTATEGENERATOR', '__EVENTVALIDATION']:
value = soup.find('input', id=key)['value']
params[key] = value
#print(key, ':', value)

# --- POST request ---

# get page with table - using params
response = s.post(url, data=params)#, headers={'Referer': url})
soup = BeautifulSoup(response.text, 'html.parser')

# --- data ---

table = soup.find('table', id='ctl00_mainContent_DataList1')

if not table:
print('no table')
#table = soup.find_all('table')
#print('count:', len(table))
#print(response.text)
else:
for row in table.find_all('table'):
for column in row.find_all('td'):
text = ', '.join(x.strip() for x in column.text.split('\n') if x.strip()).strip()
print(text)

print('-----')

部分结果:

Map
Dr. Kashyap Vora, 6145 Fraser Street, Vancouver V5W 2Z9
604 321 1869, www.voradental.ca
-----
Map
Dr. Niloufar Shirzad, Harbour Centre DentalL19 - 555 Hastings Street West, Vancouver V6B 4N6
604 669 1195, www.harbourcentredental.com
-----
Map
Dr. Janice Brennan, 902 - 805 Broadway West, Vancouver V5Z 1K1
604 872 2525
-----
Map
Dr. Rosemary Chang, 1240 Kingsway, Vancouver V5V 3E1
604 873 1211
-----
Map
Dr. Mersedeh Shahabaldine, 3641 Broadway West, Vancouver V6R 2B8
604 734 2114, www.westkitsdental.com
-----

关于python - BeautifulSoup 用 python 抓取表 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48057732/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com