【发布时间】:2020-04-25 18:30:03
【问题描述】:
我想从此数据框中获取<a href>,但我却得到了:
ValueError: Length of values does not match length of index.
这就是 DataFrame 的样子
df.head(7)
0 <ul class="toc"> <li class="first"><a href="#d...
1 <ul class="toc"> <li><a href="#d17e906">1. LEE...
2 <ul class="toc"> <li><a href="#d17e974">2.1 Be...
3 <ul class="toc"> <li><a href="#d17e6333">3.1. ...
4 <ul class="toc"> <li><a href="#d17e23490">4.1 ...
5 <ul class="toc"> <li><a href="#d17e27196">5.1 ...
6 <ul class="toc"> <li><a href="#d17e54643">Bijl...
7 <ul class="toc"> <li><a href="#d17e55852">31. ...
这是我正在使用的代码。
df = pd.read_html(url)[0]
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
ul_toc = soup.find_all('ul', class_= 'toc')
links = []
for a_tag in ul_toc:
extract= a_tag.find_all('li')
for each in extract:
try:
link = each.find('a')['href']
links.append(link)
except:
pass
df['Link'] = links
我不确定上面的代码缺少什么。
【问题讨论】:
-
您是否尝试提取文本的“a hef”值。我的意思是只有 3.1、4.1、.. 你使用的是什么 python 版本?你用的是什么熊猫版本?
-
我尝试提取 href 值。我的意思是#d17e.. 使用 Python 3.8.0 和 pandas 0.24.2
标签: python-3.x pandas dataframe valueerror