从已解析的页面中过滤 Beautiful Soup 4 结果

Filter Beautiful Soup 4 findings from parsed page

晚上,

我在想办法解决这个问题时遇到了死胡同。

简而言之,我正在使用 BS4 的 findAll() function.I 解析带有标签的产品页面得到正确的响应,但我正在搜索的区域 "plain text" 没有标签,我可以通过使用据我了解BS4

def find_product(counter):
url = base_url
print('Looking in ' + url)
while not matches[counter]:
    print(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
    try:
        response1 = search_session.get(url)
    except:
        print('Unable to connect to site...')
        if counter == checkout_qty - 1:
            sys.exit()
        else:
            continue

    soup1 = bs(response1.text, 'html.parser')
    #soup1.find_all('script')
    soup2 = soup1.findAll('script', text = re.compile('id                : ')) #using text recompiling doesn't really do anything,just gives a slightly cleaner output of findings.
    print(soup2)
    for ids in soup2:
        link = ids.find(text = re.compile('id'))
        #i think i should use it somehow here,but I lack knowledge
        #this loop is unfinished


    break

这是我从产品页面解析的内容。

<main class="B__container">
      <script>

  product.p = {
    id             : 47755536459,
    title          : "PRODUCT NAME",
    handle         : "PRODUCT HANDLE",
    vendor         : "",
    available      : ,
    images         : ["image-link.com\/files\/1111"],
    featured_image : "image-link.com\/files\/1111",
    options        : ["Size"],
    tags           : [],
    price          : 24000,
    variants       : []
  };

    product.p.variants.push({
      id                : 40113207495,
      parent_id         : 10025946759,
      available         : false,
      featured_image    : null,
      public_title      : null,
      requires_shipping : true,
      price             : 24000,
      options           : ["4"],
      option1           : "4",
      option2           : "",
      option3           : "",
      option4           : ""
    });

    product.p.variants.push({
      id                : 40113207559,
      parent_id         : 10025946759,
      available         : false,
      featured_image    : null,
      public_title      : null,
      requires_shipping : true,
      price             : 24000,
      options           : ["4.5"],
      option1           : "4.5",
      option2           : "",
      option3           : "",
      option4           : ""
    });

    product.p.variants.push({
      id                : 40113207623,
      parent_id         : 10025946759,
      available         : false,
      featured_image    : null,
      public_title      : null,
      requires_shipping : true,
      price             : 24000,
      options           : ["5"],
      option1           : "5",
      option2           : "",
      option3           : "",
      option4           : ""
    });
  </script>

我的目标是用数字提取 ID,然后将其发送到单独的函数。

问题,缺乏知识或者我缺乏如何充分利用 BS4 来获得我想要的东西的技能。

试试这个代码...它只是字符串操作来获取必要的信息..在这种情况下,id 值。

  1. \n
  2. 拆分数据
  3. for 此列表中的每个元素,检查子字符串 id 是否存在
  4. 如果True,经过几次操作后打印该行(stripsplitreplace

代码:

s = soup2.text
data = s.split('\n')

for i, d in enumerate(data):
    if " id " in d:
        print(data[i].strip().split(':')[1].replace(',', ''))

输出:

47755536459
40113207495
40113207559
40113207623

编辑代码:

for ids in soup2:
    s = ids.text
    data = s.split('\n')

    for i, d in enumerate(data):
        if " id " in d:
            print(data[i].strip().split(':')[1].replace(',', ''))

而不是 print,您可以 append 每个 id 到 list 并在以后使用它们。