猿问

网页中带有变量内部模式的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>

英特尔酷睿 i5-2400 @ 3.10GHz 是 var1 并基于此我试图获得 var2(在这一行中是 5965)


潇湘沐
浏览 226回答 1
1回答

明月笑刀无情

正如评论中所建议的,考虑使用 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 bs4soup = bs4.BeautifulSoup(html)result = soup.find(text=var1)if result:&nbsp; &nbsp; var2 = result.next.textelse:&nbsp; &nbsp; print("Not found")
随时随地看视频慕课网APP

相关分类

Python
我要回答