在webpag中具有变量内部模式的python正则表达式

2024-04-19 14:20:49 发布

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

我需要在网页代码中搜索包含两个变量的模式:一个是已知的,另一个是我试图检索的。你知道吗

def getcpu():
    parse()
    for child in rt.iter('proc'):
        proc = child.attrib['name']
        cpumodel= proc.replace('(R)',"").replace('(TM)','').replace('CPU','')
    return cpumodel

def passmark():
   url = urlopen('https://www.cpubenchmark.net/cpu_list.php').read().decode('utf-8')
   cpu = getcpu()
   soup =  BeautifulSoup(url, "html.parser")
   score = soup.find(text=cpu)
   print(score)

所以var1是已知的,必须用于搜索,var2应该以某种方式检索(当然,代码不起作用)。我把var2放在里面是因为我想解释我想要达到的目标。 有可能吗?或者除了正则表达式之外的其他方法?你知道吗

编辑: 一个更好的例子。让我们在网页中输入一行代码:

<TR id="cpu793"><TD><A HREF="cpu_lookup.php?cpu=Intel+Core+i5-2400+%40+3.10GHz&amp;id=793">Intel Core i5-2400 @ 3.10GHz</A></TD><TD>5965</TD><TD>662</TD><TD><a href="cpu.php?cpu=Intel+Core+i5-2400+%40+3.10GHz&amp;id=793#price">41.15</a></TD><TD><ahref="cpu.php?cpu=Intel+Core+i5-2400+%40+3.10GHz&amp;id=793#price">$144.99*</a></TD></TR>

Intel Core i5-2400@3.10GHz是var1,基于此,我试图得到var2(这一行中的是5965)


Tags: 代码coreid网页defproccpureplace
1条回答
网友
1楼 · 发布于 2024-04-19 14:20:49

如评论中所建议的,考虑使用BeautifulSoup:

html = '''<TR id="cpu793"><TD><A HREF="cpu_lookup.php?cpu=Intel+Core+i5-2400+%40+3.10GHz&amp;id=793">Intel Core i5-2400 @ 3.10GHz</A></TD><TD>5965</TD><TD>662</TD><TD><a href="cpu.php?cpu=Intel+Core+i5-2400+%40+3.10GHz&amp;id=793#price">41.15</a></TD><TD><ahref="cpu.php?cpu=Intel+Core+i5-2400+%40+3.10GHz&amp;id=793#price">$144.99*</a></TD></TR>'''
var1 = 'Intel Core i5-2400 @ 3.10GHz'
import bs4
soup = bs4.BeautifulSoup(html)
result = soup.find(text=var1)
if result:
    var2 = result.next.text
else:
    print("Not found")

相关问题 更多 >