0

我有一个大的 URL 文本文件(> 100 万个 URL)。URL 代表跨多个不同域的产品页面。

我正在尝试从每个 URL 中解析出 SKU 和产品名称,例如:

  • www.amazon.com/totes-Mens-Mike-Duck-Boot/dp/B01HQR3ODE/
    • 手提包-男装-Mike-Duck-Boot
    • B01HQR3ODE
  • www.bestbuy.com/site/apple-airpods-white/5577872.p?skuId=5577872
    • 苹果-airpods-白
    • 5577872

我已经找到了用于解析列表中所有域的 URL 的两个组成部分(产品名称和 SKU)的单个正则表达式模式。这是近100种不同的模式。

虽然我已经弄清楚如何一次测试这个 URL/模式,但我无法弄清楚如何构建一个脚本,该脚本将在我的整个列表中读取,然后根据相关的正则表达式遍历并解析每一行图案。任何建议如何最好地解决这个问题?

如果我的输入是一列(URL),我想要的输出是 4 列(URL、域、产品名称、SKU)。

4

2 回答 2

2

由于从 URL 中提取域名相当容易,因此您可以将域名映射到该域的模式。

像这样:

dict = {
'domain1.com': 'regex_pattern_for_domain1', 
'domain2.com': 'regex_pattern_for_domain2'
}

现在你应该逐行阅读你的文件并应用通用正则表达式来提取你将用来获取特定正则表达式的域名。

def extract_data(url, regex_pattern):
    # code to extract product name and SKU
    return ['product_id', 'sku'] 

def extract_domain(url):
    # apply general regex pattern to extract URL
    return 'domain name'

parsed_data = []
with open('urls.txt') as f:
    url = f.readline()
    domain = extract_domain(url) # call function that extracts domain from the URL
    domain_regex = dict[domain] # use dictionary to get the regex for the given domain
    data = extract_data(url, domain_regex) # call function to extract data from the given URL and regex for that domain
    data.append(domain)
    data.append(url)
    parsed_data.append(data) # append extracted data to the list, or save it to another file if it is too big to fit into memory.
于 2019-01-23T03:34:56.323 回答
1

虽然可以将这一切整合到一个庞大的正则表达式中,但这可能不是最简单的方法。相反,我会使用两遍策略。为适用于该域的正则表达式模式制作一个域名字典。在第一遍中,使用适用于所有 URL 的单个正则表达式检测该行的域。然后使用发现的域在您的 dict 中查找适当的正则表达式以提取该域的字段。

于 2019-01-23T03:27:24.160 回答