【问题标题】:Search HTML Data Retrieved from Invoke-WebRequest with Regex使用 Regex 搜索从 Invoke-WebRequest 检索的 HTML 数据
【发布时间】:2019-11-23 16:53:26
【问题描述】:

我正在尝试从 https://www.reuters.com/finance/stocks/lookup?searchType=any&comSortBy=marketcap&sortBy=&dateRange=&search=Accor 抓取数据。

最终目标是拉下包含公司、符号和交易所的表格。

我已成功获得所需的 HTML,但无法从中提取所需的数据。

我使用了一些在线 RegEx 'helpers',该字符串可以正常工作并选择我需要的数据,但是当我尝试使用该命令时它不起作用。

$web = Invoke-WebRequest -uri 'https://www.reuters.com/finance/stocks/lookup?searchType=any&comSortBy=marketcap&sortBy=&dateRange=&search=Accor' -UseBasicParsing
$str = ($web.Content).ToString()
[regex]$regex = '<table[\s\S]*?</table>'
$str | Select-String -Pattern $regex -AllMatches

$str > raw.txt; Select-String -Pattern $regex -Path ./raw.txt -AllMatches

我希望返回整个元素,但它在管道命令中返回完整字符串,而在 -Path 命令中没有任何内容。

我也尝试过使用 IE Com 对象来执行此操作。

【问题讨论】:

    标签: regex powershell select-string


    【解决方案1】:

    橡皮鸭效果。 我一问就明白了……

    $url = 'https://www.reuters.com/finance/stocks/lookup?searchType=any&comSortBy=marketcap&sortBy=&dateRange=&search=Accor'
    
    $content = (New-Object System.Net.WebClient).DownloadString($url)
    
    $content -match '<table[\s\S]*?</table>'
    
    $matches
    
    Name                           Value                                                                                                                                                                 
    ----                           -----                                                                                                                                                                 
    0                              <table width="100%" cellspacing="0" cellpadding="1" class="search-table-data">... 
    
    

    【讨论】:

    • 使用这个正则表达式更好'&lt;table\s+(?:"[\S\s]*?"|\'[\S\s]*?\'|[^&gt;]?)+&gt;([\S\s]*?)&lt;/table\s*&gt;'
    猜你喜欢
    • 2010-10-21
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    相关资源
    最近更新 更多