Eliminate unnecessary looping while parsing cable modem status table





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







0












$begingroup$


I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.



The HTML for the table looks like this (yes, it has the commented out lines)



The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.



The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is here and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.



from bs4 import BeautifulSoup
import requests

results_url = "https://pastebin.com/raw/bLZLFzy6"
content = requests.get(results_url).text

measurement = "modem"
hostname = "home-modem"


def strip_uom(data):
"""Strip Unit of Measurement

Some of our fields come with unit of measure. Rip that out and keep only
the value of the field.
"""
uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
dataset =
for d in data:
if d.split(" ")[-1] in uom:
dataset.append(d.split(" ")[0])
else:
dataset.append(d)
return dataset


soup = BeautifulSoup(content, 'html.parser')
dstable = soup.find('table', {'id': 'dsTable'})

# Pull the headers from the downstream table
# We want to make these tag friendly, so make them lowercase and remove spaces
dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]

# Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
downstream_data =
for row in dstable.find_all('tr')[1:]:
column_values = [col.get_text() for col in row.find_all('td')]
downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))

# Print line protocol lines for telegraf's inputs.exec plugin to handle
for data in downstream_data:
line_protocol_line = f"{measurement},hostname={hostname}"
fields =
for key, value in data.items():
# Check if our value is a number. If it's not, surround it in quotes.
# Don't actually use the float() value, as some numbers are returned as
# valid integers
try:
_ = float(value)
fields.append(f'{key}={value}')
except ValueError:
fields.append(f'{key}="{value}"')
fieldset = ",".join(fields)
line_protocol_line = line_protocol_line + f" channel={data['channel']} {fieldset}"
print(line_protocol_line)


Finally, the output this script generates is this:



modem,hostname=netgear-cm400 channel=1 channel=1,lock_status="Locked",modulation="QAM 256",channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19443,uncorrectables=11263
modem,hostname=netgear-cm400 channel=2 channel=2,lock_status="Locked",modulation="QAM 256",channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19531,uncorrectables=9512
modem,hostname=netgear-cm400 channel=3 channel=3,lock_status="Locked",modulation="QAM 256",channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17457,uncorrectables=9736
modem,hostname=netgear-cm400 channel=4 channel=4,lock_status="Locked",modulation="QAM 256",channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12750,uncorrectables=11156
modem,hostname=netgear-cm400 channel=5 channel=5,lock_status="Locked",modulation="QAM 256",channel_id=122,frequency=609000000,power=2.6,snr=36.3,correctables=1855538,uncorrectables=18388
modem,hostname=netgear-cm400 channel=6 channel=6,lock_status="Locked",modulation="QAM 256",channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=846194,uncorrectables=14615
modem,hostname=netgear-cm400 channel=7 channel=7,lock_status="Locked",modulation="QAM 256",channel_id=11,frequency=621000000,power=2.6,snr=37.6,correctables=281431,uncorrectables=13998
modem,hostname=netgear-cm400 channel=8 channel=8,lock_status="Locked",modulation="QAM 256",channel_id=12,frequency=627000000,power=2.4,snr=36.1,correctables=78059,uncorrectables=13695


I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in those and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?



I am running all of this code on Python 3.6.7.










share|improve this question









New contributor




NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$



















    0












    $begingroup$


    I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.



    The HTML for the table looks like this (yes, it has the commented out lines)



    The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.



    The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is here and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.



    from bs4 import BeautifulSoup
    import requests

    results_url = "https://pastebin.com/raw/bLZLFzy6"
    content = requests.get(results_url).text

    measurement = "modem"
    hostname = "home-modem"


    def strip_uom(data):
    """Strip Unit of Measurement

    Some of our fields come with unit of measure. Rip that out and keep only
    the value of the field.
    """
    uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
    dataset =
    for d in data:
    if d.split(" ")[-1] in uom:
    dataset.append(d.split(" ")[0])
    else:
    dataset.append(d)
    return dataset


    soup = BeautifulSoup(content, 'html.parser')
    dstable = soup.find('table', {'id': 'dsTable'})

    # Pull the headers from the downstream table
    # We want to make these tag friendly, so make them lowercase and remove spaces
    dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]

    # Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
    downstream_data =
    for row in dstable.find_all('tr')[1:]:
    column_values = [col.get_text() for col in row.find_all('td')]
    downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))

    # Print line protocol lines for telegraf's inputs.exec plugin to handle
    for data in downstream_data:
    line_protocol_line = f"{measurement},hostname={hostname}"
    fields =
    for key, value in data.items():
    # Check if our value is a number. If it's not, surround it in quotes.
    # Don't actually use the float() value, as some numbers are returned as
    # valid integers
    try:
    _ = float(value)
    fields.append(f'{key}={value}')
    except ValueError:
    fields.append(f'{key}="{value}"')
    fieldset = ",".join(fields)
    line_protocol_line = line_protocol_line + f" channel={data['channel']} {fieldset}"
    print(line_protocol_line)


    Finally, the output this script generates is this:



    modem,hostname=netgear-cm400 channel=1 channel=1,lock_status="Locked",modulation="QAM 256",channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19443,uncorrectables=11263
    modem,hostname=netgear-cm400 channel=2 channel=2,lock_status="Locked",modulation="QAM 256",channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19531,uncorrectables=9512
    modem,hostname=netgear-cm400 channel=3 channel=3,lock_status="Locked",modulation="QAM 256",channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17457,uncorrectables=9736
    modem,hostname=netgear-cm400 channel=4 channel=4,lock_status="Locked",modulation="QAM 256",channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12750,uncorrectables=11156
    modem,hostname=netgear-cm400 channel=5 channel=5,lock_status="Locked",modulation="QAM 256",channel_id=122,frequency=609000000,power=2.6,snr=36.3,correctables=1855538,uncorrectables=18388
    modem,hostname=netgear-cm400 channel=6 channel=6,lock_status="Locked",modulation="QAM 256",channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=846194,uncorrectables=14615
    modem,hostname=netgear-cm400 channel=7 channel=7,lock_status="Locked",modulation="QAM 256",channel_id=11,frequency=621000000,power=2.6,snr=37.6,correctables=281431,uncorrectables=13998
    modem,hostname=netgear-cm400 channel=8 channel=8,lock_status="Locked",modulation="QAM 256",channel_id=12,frequency=627000000,power=2.4,snr=36.1,correctables=78059,uncorrectables=13695


    I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in those and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?



    I am running all of this code on Python 3.6.7.










    share|improve this question









    New contributor




    NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.



      The HTML for the table looks like this (yes, it has the commented out lines)



      The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.



      The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is here and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.



      from bs4 import BeautifulSoup
      import requests

      results_url = "https://pastebin.com/raw/bLZLFzy6"
      content = requests.get(results_url).text

      measurement = "modem"
      hostname = "home-modem"


      def strip_uom(data):
      """Strip Unit of Measurement

      Some of our fields come with unit of measure. Rip that out and keep only
      the value of the field.
      """
      uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
      dataset =
      for d in data:
      if d.split(" ")[-1] in uom:
      dataset.append(d.split(" ")[0])
      else:
      dataset.append(d)
      return dataset


      soup = BeautifulSoup(content, 'html.parser')
      dstable = soup.find('table', {'id': 'dsTable'})

      # Pull the headers from the downstream table
      # We want to make these tag friendly, so make them lowercase and remove spaces
      dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]

      # Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
      downstream_data =
      for row in dstable.find_all('tr')[1:]:
      column_values = [col.get_text() for col in row.find_all('td')]
      downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))

      # Print line protocol lines for telegraf's inputs.exec plugin to handle
      for data in downstream_data:
      line_protocol_line = f"{measurement},hostname={hostname}"
      fields =
      for key, value in data.items():
      # Check if our value is a number. If it's not, surround it in quotes.
      # Don't actually use the float() value, as some numbers are returned as
      # valid integers
      try:
      _ = float(value)
      fields.append(f'{key}={value}')
      except ValueError:
      fields.append(f'{key}="{value}"')
      fieldset = ",".join(fields)
      line_protocol_line = line_protocol_line + f" channel={data['channel']} {fieldset}"
      print(line_protocol_line)


      Finally, the output this script generates is this:



      modem,hostname=netgear-cm400 channel=1 channel=1,lock_status="Locked",modulation="QAM 256",channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19443,uncorrectables=11263
      modem,hostname=netgear-cm400 channel=2 channel=2,lock_status="Locked",modulation="QAM 256",channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19531,uncorrectables=9512
      modem,hostname=netgear-cm400 channel=3 channel=3,lock_status="Locked",modulation="QAM 256",channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17457,uncorrectables=9736
      modem,hostname=netgear-cm400 channel=4 channel=4,lock_status="Locked",modulation="QAM 256",channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12750,uncorrectables=11156
      modem,hostname=netgear-cm400 channel=5 channel=5,lock_status="Locked",modulation="QAM 256",channel_id=122,frequency=609000000,power=2.6,snr=36.3,correctables=1855538,uncorrectables=18388
      modem,hostname=netgear-cm400 channel=6 channel=6,lock_status="Locked",modulation="QAM 256",channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=846194,uncorrectables=14615
      modem,hostname=netgear-cm400 channel=7 channel=7,lock_status="Locked",modulation="QAM 256",channel_id=11,frequency=621000000,power=2.6,snr=37.6,correctables=281431,uncorrectables=13998
      modem,hostname=netgear-cm400 channel=8 channel=8,lock_status="Locked",modulation="QAM 256",channel_id=12,frequency=627000000,power=2.4,snr=36.1,correctables=78059,uncorrectables=13695


      I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in those and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?



      I am running all of this code on Python 3.6.7.










      share|improve this question









      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I am writing a Python script that will be used to generate line protocol for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need.



      The HTML for the table looks like this (yes, it has the commented out lines)



      The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.



      The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is here and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.



      from bs4 import BeautifulSoup
      import requests

      results_url = "https://pastebin.com/raw/bLZLFzy6"
      content = requests.get(results_url).text

      measurement = "modem"
      hostname = "home-modem"


      def strip_uom(data):
      """Strip Unit of Measurement

      Some of our fields come with unit of measure. Rip that out and keep only
      the value of the field.
      """
      uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
      dataset =
      for d in data:
      if d.split(" ")[-1] in uom:
      dataset.append(d.split(" ")[0])
      else:
      dataset.append(d)
      return dataset


      soup = BeautifulSoup(content, 'html.parser')
      dstable = soup.find('table', {'id': 'dsTable'})

      # Pull the headers from the downstream table
      # We want to make these tag friendly, so make them lowercase and remove spaces
      dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]

      # Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
      downstream_data =
      for row in dstable.find_all('tr')[1:]:
      column_values = [col.get_text() for col in row.find_all('td')]
      downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))

      # Print line protocol lines for telegraf's inputs.exec plugin to handle
      for data in downstream_data:
      line_protocol_line = f"{measurement},hostname={hostname}"
      fields =
      for key, value in data.items():
      # Check if our value is a number. If it's not, surround it in quotes.
      # Don't actually use the float() value, as some numbers are returned as
      # valid integers
      try:
      _ = float(value)
      fields.append(f'{key}={value}')
      except ValueError:
      fields.append(f'{key}="{value}"')
      fieldset = ",".join(fields)
      line_protocol_line = line_protocol_line + f" channel={data['channel']} {fieldset}"
      print(line_protocol_line)


      Finally, the output this script generates is this:



      modem,hostname=netgear-cm400 channel=1 channel=1,lock_status="Locked",modulation="QAM 256",channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19443,uncorrectables=11263
      modem,hostname=netgear-cm400 channel=2 channel=2,lock_status="Locked",modulation="QAM 256",channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19531,uncorrectables=9512
      modem,hostname=netgear-cm400 channel=3 channel=3,lock_status="Locked",modulation="QAM 256",channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17457,uncorrectables=9736
      modem,hostname=netgear-cm400 channel=4 channel=4,lock_status="Locked",modulation="QAM 256",channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12750,uncorrectables=11156
      modem,hostname=netgear-cm400 channel=5 channel=5,lock_status="Locked",modulation="QAM 256",channel_id=122,frequency=609000000,power=2.6,snr=36.3,correctables=1855538,uncorrectables=18388
      modem,hostname=netgear-cm400 channel=6 channel=6,lock_status="Locked",modulation="QAM 256",channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=846194,uncorrectables=14615
      modem,hostname=netgear-cm400 channel=7 channel=7,lock_status="Locked",modulation="QAM 256",channel_id=11,frequency=621000000,power=2.6,snr=37.6,correctables=281431,uncorrectables=13998
      modem,hostname=netgear-cm400 channel=8 channel=8,lock_status="Locked",modulation="QAM 256",channel_id=12,frequency=627000000,power=2.4,snr=36.1,correctables=78059,uncorrectables=13695


      I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in those and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?



      I am running all of this code on Python 3.6.7.







      python python-3.x beautifulsoup






      share|improve this question









      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 1 min ago







      NewGuy













      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 14 mins ago









      NewGuyNewGuy

      1011




      1011




      New contributor




      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      NewGuy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes












          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216962%2feliminate-unnecessary-looping-while-parsing-cable-modem-status-table%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.













          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.












          NewGuy is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f216962%2feliminate-unnecessary-looping-while-parsing-cable-modem-status-table%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Сан-Квентин

          8-я гвардейская общевойсковая армия

          Алькесар