web内容的Python正则表达式

2024-04-19 21:50:24 发布

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

好的,所以我试着做一个脚本(为了我自己的娱乐),它将通过一个Kayak.co.uk使用python脚本查询并输出它。我使用urllib获取网页查询结果的内容(示例=https://www.kayak.co.uk/flights/DUB-LAX/2018-06-04/2018-06-25/2adults?sort=bestflight_a)。但是,我需要一个正则表达式来计算价格。我没怎么试过(因为我不太擅长正则表达式)。urllib也检索JS和HTML吗?我知道我需要的一些信息包含在JS中。任何帮助都将不胜感激。你知道吗

到目前为止,我的情况是:

def urlRead(url):
    """Gets and returns the content of the chosen URL"""
    webpage = urllib.request.urlopen(url) 
    page_contents = webpage.read() 
    return page_contents
def getPrices(content):
    content = re.findall(r'£435', content.decode())
    print(content)

def main():
    page_contents = ''
    url = input('Please enter in the kayak url!: ')
    content = urlRead(url)
    getPrices(content)


if __name__ == '__main__':
    main()

Tags: the脚本urlmaindefcontentspagejs
1条回答
网友
1楼 · 发布于 2024-04-19 21:50:24

正如@Mr Lister所说,如果可以避免的话,就不应该尝试使用正则表达式解析HTML。 Beautiful Soup是一个HTML解析库,可以帮助您完成所需的工作:

response = urllib2.urlopen('https://www.google.com/finance?q=NYSE%3AAAPL')
html = response.read()
soup = BeautifulSoup(html, "lxml")
aaplPrice = soup.find(id='price-panel').div.span.span.text
aaplVar = soup.find(id='price-panel').div.div.span.find_all('span')[1].string.split('(')[1].split(')')[0]
aapl = aaplPrice + ' ' + aaplVar

相关问题 更多 >