用Python从HTML中提取值

2024-09-29 20:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在从网站的HTML中提取播放器ID时遇到了一些问题。我以前做过,没有问题,但是这个特定html的href有点不同,让我很难堪。下面是HTML的一部分和我编写的脚本,它在打印后为每一行返回{}。下面的ID是'lynnla02',在HTML中出现两次,所以提取任何一个版本都可以。任何帮助都将不胜感激。你知道吗

HTML格式:

<tr data-row="248">
   <th scope="row" class="right " data-stat="ranker" csk="240">1</th>
   <td class="left " data-append-csv="lynnla01" data-stat="player">
      <a href="/players/l/lynnla01.shtml">Lance Lynn</a>

我的一个尝试:

ID = []

for tag in soup.select('a[href^=/players]'):
    link = tag['href']
    query = parse_qs(link)
    ID.append(query)

print(ID)

Tags: iddata网站htmltaglinkquerystat
1条回答
网友
1楼 · 发布于 2024-09-29 20:19:14

使用内置的

from bs4 import BeautifulSoup as bs

html = '''<tr data-row="248">
   <th scope="row" class="right " data-stat="ranker" csk="240">1</th>
   <td class="left " data-append-csv="lynnla01" data-stat="player">
      <a href="/players/l/lynnla01.shtml">Lance Lynn</a>'''

soup = bs(html, 'lxml')

hrefs = soup.find_all('a')

for a_tag in hrefs:
    if a_tag['href'].startswith('/players'):
        print(a_tag['href'])

使用正则表达式

regex = re.compile('/players.+')
a_tags = soup.find_all('a', href=regex)
#print (a_tags), you can loop for i... and do print(i['href'])

要打印您要求的特定字符串:

for i in a_tags:
    only_specific = re.match(regex, i['href'])
    print(only_specific.group(1))

相关问题 更多 >

    热门问题